Automatically create object if undefined

后端 未结 12 1046
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:42

    I use this:

    Object.prototype.initProperty = function(name, defaultValue) {
      if (!(name in this)) this[name] = defaultValue;
    };
    

    You can later do f.e.:

    var x = {a: 1};
    x.initProperty("a", 2); // will not change property a
    x.initProperty("b", 3); // will define property b
    console.log(x); // => {a: 1, b: 3}
    

提交回复
热议问题