MDN JavaScript继承重访-理解这个例子

MDN JavaScript Inheritance Revisited - understanding the example

本文关键字:JavaScript 继承 MDN      更新时间:2023-09-26

我正在看MDN页面上关于重新访问继承的示例,并认为让doSomething方法实际上一些事情会很好。因此,基于示例,我开始编写以下代码:

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.w arb不应该有一个值吗?我需要如何更改示例以使输出符合预期?

意外地指定varB不可写,因此分配this.varB = b失败(或被忽略)。

writeable: true应写成writable: true(不写e)。默认情况下,使用属性描述符定义的属性是不可写的。

所以整个描述符变成了:

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

因为你是在构造函数内部赋值的,所以你并不一定要使用描述符。


更多信息:MDN - Object.defineProperty .