Automatically create object if undefined

后端 未结 12 1044
Happy的楠姐
Happy的楠姐 2020-12-07 13:07

Is there an easy way to automatically add properties to objects if they don\'t allready exist?

Consider the following example:

var test = {}
test.hel         


        
12条回答
  •  眼角桃花
    2020-12-07 13:49

    Well you could extend the prototype of Object with a function that return a property, but adds it first, if it doesn't exist:

    Object.prototype.getOrCreate = function (prop) {
        if (this[prop] === undefined) {
            this[prop] = {};
        }
        return this[prop];
    };
    
    var obj = {};
    
    obj.getOrCreate("foo").getOrCreate("bar").val = 1;
    

提交回复
热议问题