`
gyht0808
  • 浏览: 112213 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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
 

个人博客同步更新

分享到:
评论
1 楼 superobin 2011-03-18  
貌似上次猜对了

这次说的有点简单了,建议阐述下访问和设置对象属性的机制,进而促进理解原型的一些特性。
还有内置类型 如 Object、Function、等等的原型、原型的原型是啥之类的,因为这些内置对象有些的原型是js虚拟机订死的(记得有个图来着)

另外,其实可以通过其他方式实现全继承:
function() {
    this.initialize.apply(this,arguments);
}


其中在原型中定义initialize就可以间接实现构造函数的继承了。

相关推荐

Global site tag (gtag.js) - Google Analytics