2013-02-22 63 views
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 

这到底是怎么回事?

+1

顺便提一下,您错误地输入了'A.prototype.constrcutor'。我不知道你为什么要改变它 - 你需要使用该属性跨浏览器? – 2013-02-22 14:03:07

+0

谢谢,我纠正了这个问题,尽管如此。 – CoryG 2013-02-22 14:04:52

回答

1

输入错误writable

writable: true 

按预期工作。 Fiddle

writable默认为false,所以如果输入错误的名称,它仍然是false


你怎么现在能够设置不可写的属性,并将其覆盖/阴影原型一个是没有意义的,它看起来像在Chrome实现中的错误。这种错误行为在Firefox中不可重现。

+1

爆炸拼写错误,有一些业力。 – CoryG 2013-02-22 14:19:37

相关问题