在 ColdFusion(一种服务器端语言)中,可以让 CF 为您在类中生成任何 getter 和 setter,如下所示:
component output="false" accessors="true" {
property string title;
public any function init() output = false {
setTitle("");
return this;
}
}
在这里,我从不编写 setTitle()
setter,它只是隐式的。
ES5/ES6/ES7 中的 JavaScript(甚至 jQuery)有没有这样的东西?
最佳答案
您可以为任何对象分配任意属性,而无需显式编写 setter/getter。
尽管您可以根据需要使用它们。
function myClass() {}
Object.defineProperty(myClass.prototype, "bar", {
get: function get_bar() {
return this._bar;
},
set: function set_bar(value) {
this._bar = value;
alert(value);
}
});
var instance = new myClass();
instance.foo = "123"; // Arbitary
instance.bar = "456"; // Explicit setter/getter
console.log(instance.foo, instance.bar);
关于javascript - JavaScript 中的隐式访问器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30456567/