在对象构造函数中,如何为属性附加自定义键值
From within an object constructor, how can I append an attribute with a custom key value?
我正在使用一个对象原型,我想在构造过程中使用特定键将一个新属性附加到对象上,但我不知道该怎么做。
例如:
//define module prototype
Module = function () {
for (var i = 0; i < arguments.length; i++) {
//simplified (static) example of a resource that
//would realistically be dynamically generated here
//based on the arguments
var resource = {
name: 'example name',
value: 'string of text'
};
// ! this line returns an an error that 'resources' is not defined
// - this is supposed to be the definition of it.
this.resources[resource.name] = resource;
}
};
我的目标是:
var exampleModule = new Module('exampleInput');
返回对象:
{
resources : {
'example name' : {
//resource contents here
}
}
}
希望我的问题很清楚 - 我尝试用键附加属性的问题行是:
this.resources[resource.name] = resource;
你需要做
this.resources = {};
首先,不能向未定义的引用添加属性。
您需要将
资源定义为作为模块属性的对象,然后才能设置其属性。 在进入循环之前添加以下内容:
this.resources = {}
相关文章:
- 自定义HTML元素属性未显示-Web组件
- 如何在自定义指令中获取计算的属性
- Es6:能够在设置/更新/删除对象属性时调用自定义方法
- 设置自动分隔符的自定义属性
- 其中是自定义函数中的属性
- 使用自定义数据属性或将数据绑定到处理程序来处理事件
- 与ng attr myCustomAttribute匹配的自定义属性指令
- 获取自定义属性的值
- 使用带有自定义对象作为属性的jQuery.extend时出现意外行为
- 自定义jquery选择器属性未在模拟器中激发
- Alfresco JavaScript,当文件上传到网站时,设置自定义类型属性
- 如何创建自定义属性以添加if.bind
- 如何将属性添加到自定义角度指令
- 使用水豚,i'm无法从href中读取自定义数据-属性
- 如何访问自定义 HTML 属性
- AngularJS:如何访问自定义指令中的input[date]min属性
- AngularJS将变量绑定到自定义html属性
- 动态更新Angular2指令中自定义属性的值
- C#等价于Python属性自定义/Javascript对象文本
- 如何在Angular中基于属性自定义指令模板?