我正在使用一个对象原型(prototype),并且我想在构造过程中使用特定键将新属性附加到对象上,但我不知道如何做到这一点。
例如:
//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 = {};
首先,您不能向 undefined reference 添加属性。
关于javascript - 在对象构造函数中,如何附加具有自定义键值的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075497/