简体   繁体   English

将存储在变量中的函数分配为对象文字中的getter

[英]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.

相关问题 JS 性能:function 调用 object 文字 VS object 存储在变量中 - JS performance: function call with object literal VS object stored in variable 调用存储在文字符号对象中的变量 - Calling a variable stored in a literal notation object 如何为存储对象分配功能? - How to assign function to stored object? 将全局快捷方式变量分配给全局命名空间(对象文字)是不好的做法吗? - Is it bad practice to assign a global shortcut variable to a global namespace (object literal)? 当键名由变量表示时,如何将键分配给对象文字? - How to assign key to object literal when they keyname is represented by a variable? Javascript-如何将变量用作函数和对象文字 - Javascript - how to use a variable as a function *and* an object literal 如何将 function 的返回值直接分配给 object 文字 - How to assign a return value from a function directly to an object literal 使用Object.assign()添加到对象的吸气剂会看到闭合变量的错误值? - A getter added to an object with Object.assign() sees the wrong value for a closure variable? 在javascript中声明存储在函数数组中的函数时,为变量赋值 - Assign value to a variable when declaring a function stored in a function array in javascript 在对象文字函数中访问Jquery对象变量 - acessing Jquery object variable inside object literal function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM