Arrow function and this inside a constructor function

a 夏天 提交于 2021-02-07 04:28:45

问题


I have read this paragraph about the this keyword : https://bonsaiden.github.io/JavaScript-Garden/#function.this

In this first case this refers to global objet, and it seems totally normal because when we have an arrow function, it automatically bind this with the one in the outer scope.

var obj = {
      foo : () => console.log(this)
    }
console.log(obj);
obj.foo()

However, I'm not able to explain the following behavior :

function bar(){
  this.foo = () => console.log(this)
} 

var obj = new bar()
console.log(obj);
obj.foo()

Now, this refers to obj instead of global. Why is that ? It seems to me that using the new keyword with the constructor function should return an object obj which is exactly identical as the one in the first example. And so the arrow function should have a this which refers to global and not to obj. Could you explain to me what's happening in the second case please ?


回答1:


Functions -> No separate this

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming

Read more about the new keyword here

The constructor function ... is called with the specified arguments, and with this bound to the newly created object.

The bar() constructor defines this as itself.




回答2:


Although I myself am far from good with objects (need to work on that), I think that when you do const test = new Test() you initialize a new object. That way, the scope(?) of this references only to the newly created object, thus why you do this.foo and later on you reference to that foo property by using obj.foo. On the other hand, when you just do const obj = { .... }, you don't actually initialize a new object, so the this goes straight to the global object - the window. So, const test = new Test creates a new object, while using only const obj = {} is not a new object and this by default goes to the window object.



来源:https://stackoverflow.com/questions/53146914/arrow-function-and-this-inside-a-constructor-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!