日期:2014-05-16  浏览次数:20485 次

Javascript学习笔记 What is "extend"
1. 从关于“new”的一段代码开始

从《JavaScript语言精粹》上看到一个关于“new”实现方法的猜测,实现正规,而且符合实际情况。下面把代码列下来。

Function.method('new', function(){
    // 创建一个新对象,它继承自构造器函数的原型对象。
    var that = Object.create(this.prototype);

    // 调用构造器函数,绑定 -this- 到新对象上。
    var other = this.apply(that, arguments);

    // 如果它的返回值不是一个对象,就返回该新对象。
    return (typeof other === 'object' && other) || other;
});


2. 关于继承的实现

假设上面写的正确,我们可以结合面向对象中继承的定义来实现JavaScript中的继承,即继承性是子类自动共享父类数据结构和方法的机制。

假设一个父类如下实现。
var Parent = function(x) {
    this.x = x + 1;
};
Parent.prototype.getX = function() {
    return this.x;
};


假设希望实现一个子类为Child。

子类则需要继承父类的属性和方法,根据原型链可以使用如下方法。
var Child = function() {
    //此构造函数的实现下面会讨论
};
Child.prototype = new Parent();

依据上面new的实现,Child.prototype将会被挂载到Parent类(var Parent = function(){})原型链的下面。
那么所有Parent.prototype下所有的属性都会被Child.prototype使用(var that = Object.create(this.prototype);)。
那么就会有当有如两个实现的对象。
var p = new Parent();
var c = new Child();

则,所有p的函数都会被c使用,这个情况符合继承的定义。

但是这种实现的问题是Parent的构造函数无法被继承,那么可以用如下代码实现。
var Child = function(x, y){
    //$1:下面三行实现如Java中的this.parent()方法
    this.method = Parent;
    this.method(x);
    delete this.method;

    //Child自己的构造方法中的内容。
    this.y = y;
};

总体思路是通过改变Parent中this(即函数运行环境)来实现类似于其他语言中this.parent的方法。因为就构造函数而言,父类对于子类的影响体现为构造函数所改变this下的属性和方法。
因此$1的实现方式还可以替换为以下两种方法。
Parent.call(this, x);
//或
Parent.apply(this, new Array(x));


总结以上,Child的实现如下。
var Child = function(x, y) {
    Parent.call(this, x);

    this.y = y;
};
Child.prototype = new Parent();
Child.prototype.getY = function() {
    return this.y;
}


3. Child和Parent的原型链

可以得到如下的原型链。

4. instanceof与typeof
console.log(Child.prototype.constructor === Parent); //true
console.log(typeof Parent == "function"); //true
console.log(typeof Child == "function"); //true