问题
I'd like to have a hash with params members with defaults default values:
var defaults = { item1: "def1", item2: "def2" };
var params = { item2: "param2", item3: "param3" };
var result = // some clever code here...
console.log(result); // { item1: "def1", item2: "param2", item3: "param3" };
The most clever code I can figure out is to iterate defaults members and add them into params if they are missing there. I wonder if there is some native solution instead of writing own code? Prototyping seems promising, but it only works with functional objects, which I don't want here. Any thoughts?
回答1:
If anyone is still interested: after almost two years, I guess the clever code mentioned in the question would be
__proto__: Object.create(defaults)
See the example:
var defaults = { item1: "def1", item2: "def2" };
var params = { item2: "param2", item3: "param3",
__proto__: Object.create(defaults) };
for(var i in params) console.log(i,params[i]);
// item2 param2
// item3 param3
// item1 def1
Just keep in mind that the __proto__ is deprecated, however well supported unlike the setPrototypeOf() method suggested by the link. Let's see what the future will be.
来源:https://stackoverflow.com/questions/14749020/default-hash-values