在对象构造函数中,如何为属性附加自定义键值

From within an object constructor, how can I append an attribute with a custom key value?

本文关键字:属性 自定义 键值 构造函数 对象      更新时间:2023-09-26

我正在使用一个对象原型,我想在构造过程中使用特定键将一个新属性附加到对象上,但我不知道该怎么做。

例如:

//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 = {}