【问题标题】:JavaScript Inheritance, Resetting the prototype constructor?JavaScript继承,重置原型构造函数?
【发布时间】:2017-12-08 21:19:37
【问题描述】:

这是一个实例继承的基本示例:

function A() {
    this.props = {
        a: 'a',
        b: 'b'
    }
}
A.prototype = {
    fn: function() {
        console.log(this.props);
    }
}


function B() {
    A.call(this);
}


B.prototype = Object.assign(A.prototype, {
    write: function() {
        this.fn();
    }
});

console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() { A.call(this); }

var b = new B();

下面是一个没有继承的相同函数的例子:

function A() {
    this.props = {
        a: 'a',
        b: 'b'
    }
}
A.prototype = {
    fn: function() {
        console.log(this.props);
    }
}


function B() {

}
B.prototype = {
    write: function() {
        console.log('good')
    }
}

/* 
    I don't think anyone advocates setting the prototype constructor
    as the Function to which it belongs in this case.
*/ 
console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() {}

var b = new B();

如您所见,在这两种情况下,在行之前:

B.prototype.constructor = B;

原型构造函数是原生对象构造函数,然后是声明原型的对象/函数。

对于旧浏览器来说,有问题的行是否必要,是否有必要与一些流行的不良技术作斗争,还是我没有正确地进行原型继承?

【问题讨论】:

  • 在这两种情况下,您都将使用新对象覆盖 B.prototype。所以constructor 消失了(你必须重置它)。您可以将"constructor" 属性添加到您分配给B.prototype 的对象文字中,例如:B.prototype = { constructor: B, write: ... };

标签: javascript inheritance


【解决方案1】:

感谢 Ibrahim 指出,在这两种情况下我都覆盖了 B.prototype。

鉴于此,似乎:

1.

B.prototype = Object.assign(B.prototype, A.prototype, {
    write: function() {
        this.fn();
    }
});

2.

B.prototype = Object.assign(B.prototype, {
    write: function() {
        console.log('good')
    }
});

应该保持原原型构造函数不变。

【讨论】:

  • Object.assign 在 ES2015 规范中定义,如果打算在旧浏览器中使用,您将需要一个 polyfill。另外,为什么不直接将函数附加到原始原型上呢? (B.prototype.write = fun...)
猜你喜欢
  • 1970-01-01
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多