[英]Computed Properties in node.js
I've really grown to love computed properties in Ember.js. 我真的很喜欢Ember.js中的计算属性。 What would be the closest implementation of computed properties in node.js? 在node.js中最接近的计算属性实现是什么?
EDIT: Should have been a bit more precise. 编辑:应该更精确一些。 The cool features on embers computed properties are 余烬计算属性的很酷的功能是
All this results in object definitions which are more like declarations, with little functional code but contain a lot of functionality. 所有这些都会导致对象定义更像声明,功能代码很少,但包含很多功能。
You can use standard getters / setters (available in almost every JS environment). 您可以使用标准的getter / setter方法(几乎在每个JS环境中都可用)。
var person = {
firstName: 'Mike',
lastName: 'C',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName(val) {
var valArray = val.split(/\s/);
this.firstName = valArray[0];
this.lastName = valArray[1];
return val;
}
};
console.log(person.fullName); // Mike C
person.lastName = 'Myers';
console.log(person.fullName); // Mike Myers
person.fullName = 'John Doe';
console.log(person.firstName); // John
What sets frameworks like Ember and KnockoutJS apart from vanilla JS (which is all Node.js has plus some APIs for things like I/O) is their ability to handle dependency tracking. 使Ember和KnockoutJS之类的框架与普通JS(这是Node.js所拥有的,再加上一些用于I / O之类的API)区别开来的原因在于它们处理依赖关系跟踪的能力。 Dependency tracking is not provided out of the box. 没有立即提供依赖项跟踪。 There was a proposal for Object.observe
which would allow for dependency tracking (which you'd still have to do some work yourself) but has since been removed from the standard so don't plan on using it. 有一个Object.observe
提案,该提案允许进行依赖项跟踪(您仍然需要自己做一些工作),但此后已从标准中删除,因此不打算使用它。
Take a look at Object.defineProperies
or Object.definePropery
. 看一下Object.defineProperies
或Object.definePropery
。 They will allow you to define a getter and setter for a property of an object. 它们将允许您为对象的属性定义获取器和设置器。
var person = { first: 'John', last: 'Doe' };
Object.defineProperty(person, 'fullName', {
get: function(){ return this.first + ' ' + this.last },
set: function(val){
var pair = val.split(/\s/);
this.first = pair[0];
this.last = pair[1];
return val;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.