javascript继承之借用构造函数(二)

 1 //简单的函数调用
 2         function Father() {
 3             this.nums= [1,2];
 4         }
 5         function Son() {
 6             Father.call(this);//调用超类型,完成son继承father
 7         }
 8         var s1 = new Son();
 9         s1.nums.push("yellow");
10         alert(s1.nums);//red,black,yellow
11         var s2 = new Son();
12         alert(s2.nums); //red,black

每次实例化son的时候,father都会在新的环境下被调用,每个son的实例都会具有属于自己的nums副本.        

 1 //向父类传参
 2         function Human(name) {
 3             this.name = name;
 4         }
 5         function Man(name,age) {
 6             Human.call(this, name);
 7             this.age = age;
 8         }
 9         var yaoMing = new Man("姚明",42); 
10         alert(yaoMing.name);//姚明
11         alert(yaoMing.age);//42

子类可以向父类中传递参数了.这就使得原型链继承得到了改善.
这种方式,所有的方法都在构造函数中定义,那么属性的共享就无从谈起了.
这个问题将在下一章的组合继承得到解决

posted @ 2014-03-12 09:32  思思博士  阅读(258)  评论(0编辑  收藏  举报