[英]Assign function stored in variable as getter in object literal
Say I have a function. 说我有一个功能。 If I wanted to add it as a method to an object, I would use:
如果我想将其作为方法添加到对象,则可以使用:
let foofunc = function() {}
{
foo: foofunc
}
However, what if I want to add it as a getter? 但是,如果我想将其添加为吸气剂怎么办? You'd think I could do it like this:
您可能以为我可以这样:
{
get x: foofunc
}
but my IDE complains, so I assume that's not possible. 但是我的IDE抱怨,所以我认为这是不可能的。 How would I do this?
我该怎么做?
You can use the Object.defineProperty
function like so: 您可以像这样使用
Object.defineProperty
函数:
function getterFunc() { return 1; }
let anObject = {};
Object.defineProperty(anObject, 'propertyName', {get: getterFunc});
Live Example: 现场示例:
function getterFunc() { return 1; } let anObject = {}; Object.defineProperty(anObject, 'propertyName', {get: getterFunc}); console.log(anObject.propertyName); // 1
You can access use the getter normally by doing anObject.propertyName
. 您可以通过执行
anObject.propertyName
正常使用getter。 The MDN page has more detailed information if you still have more questions. 如果您还有其他问题,则MDN页面包含更多详细信息。
To make it as getter function.. 使其成为吸气功能。
let foofunc = function() { return this.x;}
let obj = {
x: "marvel",
get foo(){return foofunc.call(this)}
};
use: 采用:
console.log(obj.foo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.