您现在的位置: 网页制作教程网 >> 网页特效 >> Javascript 教程 >> 正文
| 以下是引用片段: 1 function Person(name) //基类构造函数 2 { 3 this.name = name; 4 }; 5 6 Person.prototype.SayHello = function() //给基类构造函数的prototype添加方法 7 { 8 alert("Hello, I'm " + this.name); 9 }; 10 11 function Employee(name, salary) //子类构造函数 12 { 13 Person.call(this, name); //调用基类构造函数 14 this.salary = salary; 15 }; 16 17 Employee.prototype = new Person(); //建一个基类的对象作为子类原型的原型,这里很有意思 18 19 Employee.prototype.ShowMeTheMoney = function() //给子类添构造函数的prototype添加方法 20 { 21 alert(this.name + " $" + this.salary); 22 }; 23 24 var BillGates = new Person("Bill Gates"); //创建基类Person的BillGates对象 25 var SteveJobs = new Employee("Steve Jobs", 1234); //创建子类Employee的SteveJobs对象 26 27 BillGates.SayHello(); //通过对象直接调用到prototype的方法 28 SteveJobs.SayHello(); //通过子类对象直接调用基类prototype的方法,关注! 29 SteveJobs.ShowMeTheMoney(); //通过子类对象直接调用子类prototype的方法 30 31 alert(BillGates.SayHello == SteveJobs.SayHello); //显示:true,表明prototype的方法是共享的 |
| 以下是引用片段: function Person(name) { this.name = name; }; Person.prototype.company = "Microsoft"; //原型的属性 Person.prototype.SayHello = function() //原型的方法 { alert("Hello, I'm " + this.name + " of " + this.company); }; var BillGates = new Person("Bill Gates"); BillGates.SayHello(); //由于继承了原型的东西,规规矩矩输出:Hello, I'm Bill Gates var SteveJobs = new Person("Steve Jobs"); SteveJobs.company = "Apple"; //设置自己的company属性,掩盖了原型的company属性 SteveJobs.SayHello = function() //实现了自己的SayHello方法,掩盖了原型的SayHello方法 { alert("Hi, " + this.name + " like " + this.company + ", ha ha ha "); }; SteveJobs.SayHello(); //都是自己覆盖的属性和方法,输出:Hi, Steve Jobs like Apple, ha ha ha BillGates.SayHello(); //SteveJobs的覆盖没有影响原型对象,BillGates还是按老样子输出 |
上一页 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 下一页
我来说两句:
推荐文章
相关文章