Object.defineProperty获取/设置闭包 [英] Object.defineProperty get/set closure

查看:351
本文介绍了Object.defineProperty获取/设置闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  var src = {a:'a',b: 'b',c:'c'}; 
var out = {};
(src中的var prop){
Object.defineProperty(out,prop,{
get:function(){
return src [prop];
} ,
set:function(val){
src [prop] = val;
}
})
}



$ b

{a:'c',b:'c',c:'c'}

我知道其他方法来创建这个对象,例如:
$ b $ pre $ for(var prop in src){
(function(prop ){
Object.defineProperty(out,prop,{
get:function(){
return src [prop];
},
set:function(val ){
src [prop] = val;
}
})
})(prop)
}

或者:

  Object.keys(src)。 map(function(prop){
Object.defineProperty(out,prop,{
get:function(){
返回src [道具];
},
set:function(val){
src [prop] = val;

})
})

理解为什么,在第一种方法中,字符串参数prop将通过链接发送到函数'defineProperty'。请帮助我理解这一点。
对不起英文不好。

解决方案

当你在一个循环中创建一个函数时,在那个循环中。在这种情况下,围绕 prop 有一个闭包。每个函数(getters)都有一个对 prop 的引用,所以当它们被稍后调用时(当使用getter时),它们使用 prop中的值恰好是在循环中分配的最后一个值。换句话说,由于稍后调用getter,所以 prop 中的值是它最后一次设置的值至。另一方面, defineProperty 由于没有关闭而获得正确的值。它在调用时被调用,而不是在循环完成后调用。


Ok, I try to create new object this way:

var src = {a:'a', b:'b', c:'c'};
var out = {};
for(var prop in src){   
    Object.defineProperty(out, prop,{
        get: function(){
            return src[prop];
        },
        set: function(val){
            src[prop]=val;
        }
    })
}

And get a bad result:

out = {a:'c', b:'c', c:'c'}

I know other ways to create this object, so as:

for (var prop in src) {
    (function(prop) {
        Object.defineProperty(out, prop, {
            get: function() {
                return src[prop];
            },
            set: function(val) {
                src[prop] = val;
            }
        })
    })(prop)
}

or:

Object.keys(src).map(function(prop){
    Object.defineProperty(out, prop,{
        get: function(){
            return src[prop];
        },
        set: function(val){
            src[prop]=val;
        }
    })
})

But I can't understand why, in the first method, a string parameter "prop" will be sent to the function 'defineProperty' by link. Help me to understand this please. Sorry for bad english.

解决方案

When you create a function inside a loop you create a closure around the variables used in that loop. In this case there is a closure around prop. Each function (the getters) has a reference to prop so when they are called later on (when the getter is used) they use the value in prop which happens to be the last value that was assigned in the loop.

In other words, since the getter is called later, the value in prop is whatever value it was last set to. defineProperty, on the other hand, gets the correct value since there is no closure. It is called with the value at the time of the call rather than after the loop is complete.

这篇关于Object.defineProperty获取/设置闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆