JavaScript读书笔记六

 

原型链是实现继承的主要方法。基本思想是利用原型让一个引用类型继承另一个引用类型的属性和方法。

 

function SuperType() {
    this.property = true;
}

SuperType.prototype.getSuperValue = function () {
    return this.property;
}

function SubType() {
    this.subproperty = false;
}

SubType.prototype = new SuperType();

SubType.prototype.getSubValue = function() {
    return this.subproperty;
}
var instance = new SubType();
alert(instance.getSuperValue()); // true

alert(instance instanceof Object); // true
alert(instance instanceof SuperType); // true
alert(instance instanceof SubType); // true

alert(Object.prototype.isPrototypeOf(instance)); // true
alert(SuperType.prototype.isPrototypeOf(instance)); // true
alert(SubType.prototype.isPrototypeOf(instance)); // true
 

实现的本质是重写原型对象,代之以一个新类型的实例。给原型添加方法的代码一定要放在替换原型的语句之后,在通过原型链实现继承时,不能使用对象字面量创建原型方法,因为这样就会重写原型链。

通过原型来实现继承时,原型实际上会变成另一个类型的实例,实例会恭喜。而且在创建子类型的时候,不能向超类型的构造函数传递参数。

使用使用一种叫做借用构造函数的技术,解决了原型中包含引用类型值所带来问题。

 

function SuperType(name) {
    this.colors = ["red", "green", "blue"];
    this.name = name;
}
function SubType() {
    // 继承了SuperTyle, 同时还传递了参数
    SuperType.call(this, "Miles");
    this.age = 24;
}

var instance1 = new SubType();
instance1.colors.push("black");
alert(instance1.colors); //  "red,green,blue,black"
alert(instance1.name); // "Miles"
alert(instance1.age); //  24

var instance2 = new SubType();
alert(instance2.colors); // "red,green,blue"
 

借用构造函数的方法都在构造函数中定义,因此函数的复用的问题没法解决。

 

组合继承,指的是讲原型链和借用构造函数的技术组合到一起,使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。

 

 

function SuperType(name) {
    this.colors = ["red", "blue", "green"];
    this.name = name;
}

SuperType.prototype.sayName = function() {
    alert(this.name);
}
function SubType(name, age) {
    // 继承了SuperTyle, 同时还传递了参数
    SuperType.call(this, name);
    this.age = age;
}

SubType.prototype = new SuperType();
SubType.prototype.sayAge = function() {
    alert(this.age);
}
var instance1 = new SubType("Miles", 24);
instance1.colors.push("black");
alert(instance1.colors); //  "red,blue,green,black"
instance1.sayName(); // "Miles"
instance1.sayAge();  // 24

var instance2 = new SubType("Jenny", 24);
alert(instance2.colors); // "red,blue,green"
instance2.sayName(); // "Jenny"
instance2.sayAge();  // 24
 

个人博客同步更新

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值