2

我正在查看 MDN 页面上关于Inheritance RevisiteddoSomething的示例,并认为让这些方法真正一些事情会很好。所以我从以下代码开始,基于示例:

function A(a) { this.varA = a };
A.prototype = { varA: null, doSomething: function() { console.log('do something with ' + this.varA) } };
function B(a, b) {
    A.call(this, a);
    this.varB = b;
};
B.prototype = Object.create(new A(), {
    varB: { value: null, enumerable: true, configurable: true, writeable: true },
    doSomething: { value: function() {
        A.prototype.doSomething.apply(this, arguments);
        console.log("do something with " + this.varB);
    }, enumerable: true, configurable: true, writeable: true}
});
var b = new B('a', 'b');
b.doSomething();

我将代码复制并粘贴到 Chrome 控制台中,预计会看到

do something with a
do something with b

但相反我得到了

do something with a
do something with null

我在这里俯瞰什么?对“new B”的调用不应该导致上面定义的构造函数(函数B(...))被调用吗?如果构造函数被调用,b.varB 不应该有一个值吗?我如何需要更改示例以使输出符合预期?

4

1 回答 1

2

Accidentally you specified varB as being non-writable and hence the assignment this.varB = b failed (or was ignored).

writeable: true should be spelled writable: true (without e). By default, properties defined using the a property descriptor are non-writable.

So the whole descriptor becomes:

varB: { value: null, enumerable: true, configurable: true, writable: true }

Since you are assigning a value inside the constructor function anyway, you don't really have to use the descriptor though.


More information: MDN - Object.defineProperty.

于 2013-01-20T21:15:49.137 回答