Object.defineProperty get/set closure

后端 未结 1 1356
有刺的猬
有刺的猬 2021-01-14 01:33

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,{
         


        
相关标签:
1条回答
  • 2021-01-14 01:57

    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.

    0 讨论(0)
提交回复
热议问题