我希望功能类似于获取C#.net的属性。例如
var method : function() {
return "something which always change";
},
var objectName = {
property : method()
};
所以每当我调用objectName.property时,都会返回实际的新值。不是声明时设定的值。可能吗。
在.net属性中保存函数地址,每次调用该函数。我想要这样的功能。
感谢,
答案 0 :(得分:1)
使用Object.defineProperty覆盖getter。
var counter = 0;
var method = function() {
return counter++;
};
function ObjectName() {}
Object.defineProperty(ObjectName.prototype, 'property', {
get: method
});
var objectName = new ObjectName();
console.log(objectName.property); // 0
console.log(objectName.property); // 1
答案 1 :(得分:1)
以.net c#style更像这样写的方式是
var o = {
a: 7,
get b() {
return this.a + 1;
},
set c(x) {
this.a = x / 2
}
};
console.log(o.a); // 7
console.log(o.b); // 8
o.c = 50;
console.log(o.a); // 25
答案 2 :(得分:-1)
出于OOP
原因,您应该将object
视为.Net中的Class
。
例如:
var Superman = function () {
this.quality = 'charming';
this.height = "6'5\"";
this.fly = function() {
console.log('flying..');
}
this.save = function(name) {
console.log('Save ' + name);
}
return this;
};
var CK = Superman();
console.log(CK.quality);
CK.save('L. Lane');