1

仅在 Chrome 中对此进行了测试,我的应用程序不需要在任何其他浏览器中运行。

例如在以下代码 ( JSFiddle ) 中:

function A(a) {
    document.write(this.B);
    this.A = a;
    this.B = a;
}
function A_C(a) {
    this.A = a;
    this.B = a;
}
A.prototype.constructor = A;
A.prototype.C = A_C;
Object.defineProperty(A.prototype, 'B', {
    writeable: true,
    enumerable: true,
    value: '0'
});

var B = A;

var C = new A('A');
var D = new B('B');

document.write(C.A);
document.write(D.A);
document.write(C.B);
document.write(D.B);

C.C('C');
D.C('D');

document.write(C.A);
document.write(D.A);
document.write(C.B);
document.write(D.B);

输出是:

00AB00CD00

代替:

00ABABCDCD

而在以下代码(JSFiddle)中:

function A(a) {
    this.A = a;
    this.B = a;
}
function A_C(a) {
    this.A = a;
    this.B = a;
}
A.prototype.constructor = A;
A.prototype.C = A_C;
Object.defineProperty(A.prototype, 'B', {
    writeable: true,
    enumerable: true,
    value: '0'
});

var B = A;

var C = new A('A');
var D = new B('B');

document.write(C.A);
document.write(D.A);
document.write(C.B);
document.write(D.B);

C.C('C');
D.C('D');

document.write(C.A);
document.write(D.A);
document.write(C.B);
document.write(D.B);

输出是:

ABABCDCD

这里发生了什么?

4

1 回答 1

1

你打错了writable

writable: true

按预期工作。小提琴

writable默认情况下是false,所以如果名称输入错误,它仍然是false.


如何设置不可写属性并覆盖/隐藏原型是没有意义的,它看起来像是 Chrome 实现中的一个错误。这种错误行为在 Firefox 中是不可重现的。

于 2013-02-22T14:11:44.293 回答