Javascript属性get和set类似于c#.net
Javascript property get and set similar to c# .net
我想要一些类似于C#.net的get属性的功能。例如
var method : function() {
return "something which always change";
},
var objectName = {
property : method()
};
因此,每当我调用objectName.properties时,它都应该返回实际的新值。而不是在声明时设置的值。有可能吗。
在.net属性中,保存函数地址,每次调用该函数。我想要这样的功能。
谢谢,
使用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
JSBin演示https://jsbin.com/racegeteni/edit?js,控制台
用更像.net c#风格的其他方法是
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
由于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');
相关文章:
- Javascript日期格式类似于ISO,但本地
- toBoolean方法类似于toString
- 州和城市选择框类似于国家细分页面
- 通过传递图像的URL通过javascript读取/处理图像-类似于PHP中的file_get_contents
- 在BootStrap菜单栏中为所选项目设置背景,类似于BootStrap中的父导航选项
- 检测演示者工具的事件,类似于onmousedown
- 类似于Prism的Knockout js框架
- 创建类似于Google analytics的分析地图
- 敲除js变量设置类似于调用函数
- 如何处理javascript中的循环引用,类似于Excel提供迭代限制的方式
- 用null填充稀疏数组(类似于压缩两个数组)
- jQuery模态弹出的行为类似于确认和警报对话框
- 如何垂直淡出文本,类似于Amazon'的产品说明
- 如何在JavaScript中创建类似于something.function()的函数
- 使Dockerfile VOLUME的行为类似于docker compose volumes
- TypeScript代码类似于揭示模块模式结构
- 类似于母版页 asp.net 客户端解决方案
- Javascript属性get和set类似于c#.net
- 是否有类似于Node.js中使用的stream.on('data')的.net Core ?
- JS到文本模板引擎(类似于asp.net)