我正在尝试找到一种初始化属性值的方法,该属性值附加到具有本地化值引用的JavaScript伪类的所有实例,而无需手动迭代每个实例,例如以下代码:
function A() {
this.a = '0';
}
var a = new A();
var b = new A();
document.write(a.a + a.b + a.c + '<BR />');
A.prototype.b = '1';
Object.defineProperty(A.prototype, 'c', {
writable: true,
value: (function() { return(this.a + '|'); })()
});
document.write(a.a + a.b + a.c + '<BR />');
b.c = '3';
document.write(a.a + a.b + a.c + '<BR />');
document.write(b.a + b.b + b.c + '<BR />');
输出:
0undefinedundefined
01undefined|
01undefined|
013
但在所需条件下输出:
0undefinedundefined
010|
010|
013
编辑:
为了澄清,应该将值初始化为通过“this”访问的对象的属性。当属性附加到对象时,不是在get或set调用上以延迟方式并且不使用其他本地属性。
答案 0 :(得分:1)
如果您希望能够访问this
,则无法使用value
和writable
描述符选项。您需要使用get
和set
。在这种情况下,由于您希望分配的值优先于默认值,因此您需要执行该逻辑。
Object.defineProperty(A.prototype, 'c', {
get: function(){
// If an overridden values was provided, then return that instead.
if ('_c' in this) return this._c;
return (this.a + '|');
},
set: function(val){
this._c = val;
}
});
答案 1 :(得分:1)
您似乎想要一个动态计算a
属性值的getter函数:
Object.defineProperty(A.prototype, 'c', {
get: function() {
return(this.a + '|');
},
set: function(x) { // overwritable:
// create normal property directly on the object (not on the prototype)
Object.defineProperty(this, 'c', {
value: x,
writable: true
});
}
});
您当前的代码就像
一样A.prototype.c = (function() { return(this.a + '|'); })(); // IEFE
其中this
是全局对象,a
当然是未定义的。