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

查看:24
本文介绍了Object.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;
        }
    })
}

得到一个糟糕的结果:

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)
}

或:

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

但我不明白为什么在第一种方法中,字符串参数prop"会通过链接发送到函数defineProperty".请帮助我理解这一点.抱歉英语不好.

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.

推荐答案

当您在循环内创建函数时,您会在该循环中使用的变量周围创建一个闭包.在这种情况下,prop 周围有一个闭包.每个函数(getter)都有一个对 prop 的引用,所以当它们稍后被调用时(当使用 getter 时)它们使用 prop 中的值,它恰好是在循环中分配的最后一个值.

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.

换句话说,由于稍后调用 getter,prop 中的值是它上次设置的任何值.defineProperty 另一方面,因为没有闭包,所以得到正确的值.使用调用时的值而不是在循环完成后调用它.

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天全站免登陆