Javascript automatic getter/setters (John Resig Book)

前端 未结 8 665
陌清茗
陌清茗 2020-12-14 03:02

I\'m reading \"Pro Javascript Techniques\" from John Resig, and I\'m confused with an example. This is the code:

// Create a new user object that accepts an          


        
8条回答
  •  执念已碎
    2020-12-14 03:17

    I started this post with the sole purpose of learning why that things happened, and I finally did. So in case there's someone else interested in the "whys" here they are:

    Why does 'this' changes inside the anonymous function?

    A new function, even if it is an anonymous, declared inside an object or another function ALWAYS CHANGES THE SCOPE, in this case returning to the global scope (window)

    Solution: all stated in the post, I think the clearer is executing the anonymous function with .call(this)

    Why getname() always returns the age?

    While the anonymous function gets executed right away, the getters/setters get executed for the first time when they are called. In that moment, the value of i will always be the last because it has already iterated for all the properties... and will always return properties[i] which is the last value, in this case the age.

    Solution: save the i value in a variable like this

     for ( i in properties ) { (function(){ 
      var j = i
      //from now on use properties[j]
    

    That's basically it, if I'm wrong in anything I said please correct me, since I'm trying to learn this...

    Thanks again.

提交回复
热议问题