日期:2014-05-16 浏览次数:20603 次
Function.method('new', function(){
    // 创建一个新对象,它继承自构造器函数的原型对象。
    var that = Object.create(this.prototype);
    // 调用构造器函数,绑定 -this- 到新对象上。
    var other = this.apply(that, arguments);
    // 如果它的返回值不是一个对象,就返回该新对象。
    return (typeof other === 'object' && other) || other;
});
var Parent = function(x) {
    this.x = x + 1;
};
Parent.prototype.getX = function() {
    return this.x;
};
var Child = function() {
    //此构造函数的实现下面会讨论
};
Child.prototype = new Parent();
var p = new Parent(); var c = new Child();
var Child = function(x, y){
    //$1:下面三行实现如Java中的this.parent()方法
    this.method = Parent;
    this.method(x);
    delete this.method;
    //Child自己的构造方法中的内容。
    this.y = y;
};
Parent.call(this, x); //或 Parent.apply(this, new Array(x));
var Child = function(x, y) {
    Parent.call(this, x);
    this.y = y;
};
Child.prototype = new Parent();
Child.prototype.getY = function() {
    return this.y;
}

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