在对象构造函数中,我如何附加一个带有自定义键值的属性?
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');
到return一个对象:
{
resources : {
'example name' : {
//resource contents here
}
}
}
希望我的问题很清楚 - 我尝试用键附加属性的有问题的行是:
this.resources[resource.name] = resource;
你需要做的
this.resources = {};
首先,您不能向未定义的引用添加属性。
您需要将资源定义为模块的 属性 对象,然后才能设置其属性。在进入循环之前添加:
this.resources = {}
我正在使用一个对象原型,我想在构造过程中使用特定键将一个新属性附加到一个对象上,但我不知道该怎么做。
例如:
//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');
到return一个对象:
{
resources : {
'example name' : {
//resource contents here
}
}
}
希望我的问题很清楚 - 我尝试用键附加属性的有问题的行是:
this.resources[resource.name] = resource;
你需要做的
this.resources = {};
首先,您不能向未定义的引用添加属性。
您需要将资源定义为模块的 属性 对象,然后才能设置其属性。在进入循环之前添加:
this.resources = {}