js继承-来自js高级

继承:组合继承(原型继承与借用构造函数):用构造函数实现对实例属性的继承,用原型链实现对原型属性和方法的继承

function Super(name) {

this.name = name;

this.colors = ["yellow", "red"];

}

Super.prototype.sayName = function() {

alert(this.name);

}

function Sub(name, age) {

Super.call(this, name); // 第二次调用Super

this.age = age;

}

Sub.prototype = new Super(); // 第一次调用Super

Sub.prototype.constructor = Sub;

Sub.prototype.sayAge = function() {

alert(this.age);

}



var instance1 = new Sub("Hello Kitty", 20);

instance1.colors.push("green");

console.log("1:",instance1.colors);

instance1.sayName();

instance1.sayAge();



var instance2 = new Sub("LiLei", 30);

console.log("2:",instance2.colors);

instance2.sayName();

instance2.sayAge();

问题:父类构造函数调用了两次,解决此问题,采用寄生组合式继承

 

寄生组合式继承:--最常用的继承方式

function object(o) { // 创建对象的副本

function F() {

}

F.prototype = o;

return new F();

}

function inheritPrototype(Sub, Super) {

var protype = object(Super.prototype);

protype.constructor = Sub;

Sub.prototype = protype;

}

function Super(name) {

this.name = name;

this.colors = ["yellow", "red"];

}

Super.prototype.sayName = function() {

alert(this.name);

}

function Sub(name, age) {

Super.call(this, name); // 第二次调用Super

this.age = age;

}

inheritPrototype(Sub, Super);

Sub.prototype.constructor = Sub;

Sub.prototype.sayAge = function() {

alert(this.age);

}

var instance1 = new Sub("Hello Kitty", 20);

instance1.colors.push("green");

console.log("1:",instance1.colors);

instance1.sayName();

instance1.sayAge();



var instance2 = new Sub("LiLei", 30);

console.log("2:",instance2.colors);

instance2.sayName();

instance2.sayAge();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值