我有一个代码如下, 有没有更简单的方法在 JavaScript 中编写 Object.defineProperty ?
Object.defineProperty(window, "world",
{
set: function(w)
{
return w();
}
});
谢谢!
最佳答案
试试这个:
Object.defineProperties(window, {
propertyOne: {
get: function(){ },
set: function(i){ ... }
},
propertyTwo: {
get: function(){ },
set: function(i){ ... }
},
propertyThree: {
get: function(){ },
set: function(i){ ... }
}
});
相当于:
Object.defineProperty(window, "propertyOne", {
get: function(){ },
set: function(i){ ... }
});
Object.defineProperty(window, "propertyTwo", {
get: function(){ },
set: function(i){ ... }
});
Object.defineProperty(window, "propertyThree", {
get: function(){ },
set: function(i){ ... }
});
在将函数分配给对象文字时(例如设置 JavaScript 函数的原型(prototype)时),也可以使用 get/set 关键字:
var Example = function(element){
this.element = element;
};
Example.prototype = {
get colour(){ return this.element.style.backgroundColor; },
set colour(i){ this.element.style.backgroundColor = i; }
}
关于javascript - 有没有更简单的方法在 JavaScript 中编写 Object.defineProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27986320/