javascript - 在对象构造函数中,如何附加具有自定义键值的属性?

标签 javascript prototype

我正在使用一个对象原型(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/

相关文章:

javascript - 带有 eventListener 的原型(prototype)内的 Array.from(..) 不起作用

javascript - jQuery + 扩展 Object.prototype = "c.replace is not a function"

javascript - JS中这三种声明方法的方式有什么区别吗?

javascript - 如何将参数传递给模块模式

javascript - 列系列顶部预定位置的项目符号(不是列系列值)

Javascript部分应用

javascript - 快速 js session 中的未定义错误

javascript - 带有 socketio : wht doesn't publisher publish message? 的 nodejs 中的 redis pubsub

Javascript 连接 2 个数组

javascript - 通过原型(prototype)扩展数学对象不起作用