箭头函数和此函数在构造函数中 [英] Arrow function and this inside a constructor function
问题描述
我已阅读本段有关this关键字的内容: https://bonsaiden.github.io/JavaScript-Garden/#function.this
I have read this paragraph about the this keyword : https://bonsaiden.github.io/JavaScript-Garden/#function.this
在第一种情况下, this
是指 global
对象,这似乎是完全正常的,因为当我们具有箭头功能时,它会自动绑定 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()
现在,此
是指 obj
,而不是 global
.这是为什么 ?在我看来,将 new
关键字与构造函数一起使用应该返回一个对象 obj
,该对象与第一个示例中的对象完全相同.因此,箭头函数应该有一个 this
,它引用 global
而不是 obj
.你能告诉我第二种情况是怎么回事吗?
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 ?
推荐答案
函数->
在箭头函数之前,每个新函数都定义了自己的此值(对于构造函数而言,是 新对象 ,在
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
使用指定的参数调用构造函数...,并使用 this
绑定到 新创建的对象 .
The constructor function ... is called with the specified arguments, and with this
bound to the newly created object.
bar()构造函数将 this
本身定义为.
The bar() constructor defines this
as itself.
这篇关于箭头函数和此函数在构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
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
使用指定的参数调用构造函数...,并使用
this
绑定到 新创建的对象 .
The constructor function ... is called with the specified arguments, and with
this
bound to the newly created object.
bar()构造函数将 this
本身定义为.
The bar() constructor defines this
as itself.
这篇关于箭头函数和此函数在构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!