1
只在Chrome中进行测试,我的应用程序不需要在任何其他浏览器中工作。为什么Object.defineProperty定义的属性的行为在使用之前被访问时会发生变化?
例如,在下面的代码(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
这到底是怎么回事?
顺便提一下,您错误地输入了'A.prototype.constrcutor'。我不知道你为什么要改变它 - 你需要使用该属性跨浏览器? – 2013-02-22 14:03:07
谢谢,我纠正了这个问题,尽管如此。 – CoryG 2013-02-22 14:04:52