function A(params) {
params = params || {};
for(var key in params){
Object.defineProperty(this, key, {
get : function() {
return params[key]
},
enumerable : false
});
}
}
var a = new A({
'x' : 'X',
'y' : 'Y',
'z' : 'Z'
})
console.log(a.x);
The result is Z, which is a bit hard to understand. The console output example is as follows:
The reason is actually very simple, the problem lies in the for loop
The final key here === 'z', and the results of other attributes return params[key], which is params['z']
This is an object copy function. The only difference from the original object is that the attributes of the copied object a cannot be traversed using a for loop. Because of the closure, the keys called by the get function are all z.
a= {
}
Create a closure, or use let
Or change var key to let key
here,
Object.defineProperty(this, key, {})
这里的key
是立即读取使用的,所以是预期行为x,y,z
This function is executed at a point in time in the future, so it reads the last
key
值,即z
when running. This is the same as the classic closure problem.Everything printed is 5.