箭头功能和这个 [英] Arrow Functions and This
问题描述
var person = {
name:jason,
shout:()=> console.log(我的名字是,this.name)
}
person.shout()//应该打印出我的名字是jason
但是,当我运行这个代码控制台时,只有日志我的名字是
。我做错了什么?
简短答案: 更长的回答:创建 绑定 更清楚的是,将其翻译成ES5中箭头语法的模糊近似: 在这两种情况下, 您不能使箭头功能以这种方式工作,但是,正如@kamituel在他的答案,您可以利用ES6中较短的方法声明模式来获得类似的空间节省: I'm trying out ES6 and want to include a property inside my function like so However, when I run this code console only logs Short answer: Longer answer: Arrow functions And even more clear when translated into a vague approximation of the arrow syntax in ES5: In both cases, You cannot make arrow functions work that way, but, as @kamituel points out in his answer, you can take advantage of the shorter method declaration pattern in ES6 to get similar space savings:
这篇关于箭头功能和这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!这个
中的 c $ c> 在中提供的代码 b
这个
.getify.com / arrow-this /rel =nofollow noreferrer>没有这个
,参数
或其他特殊名称绑定 - 当对象被创建时,名称这个
被发现在封闭的范围内,而不是 person
object。您可以通过移动声明来更清楚地看到这一点:
var person = {
name =Jason
};
person.shout =()=> console.log(我的名字是,这个);
var person = {
name =Jason
};
var shout = function(){
console.log(我的名字是,this.name);
} .bind(this);
person.shout = shout;
这个
呼叫功能)指向与人
的定义相同的范围,而不是将该函数添加到人时附加到的新范围
对象。
var person = {
name:Jason,
// ES6method离开:和函数
shout(){
console.log(我的名字是,this.name);
}
};
var person = {
name: "jason",
shout: () => console.log("my name is ", this.name)
}
person.shout() // Should print out my name is jason
my name is
. What am I doing wrong?this
points at the nearest bound this
- in the code provided this
is found in the enclosing scope.bind their do not have this
when they are createdthis
, arguments
or other special names bound at all - when the object is being created the name this
is found in the enclosing scope, not the person
object. You can see this more clearly by moving the declaration:var person = {
name = "Jason"
};
person.shout = () => console.log("Hi, my name is", this);
var person = {
name = "Jason"
};
var shout = function() {
console.log("Hi, my name is", this.name);
}.bind(this);
person.shout = shout;
this
(for the shout function) points to the same scope as person
is defined in, not the new scope that the function is attached to when it is added to the person
object.var person = {
name: "Jason",
// ES6 "method" declaration - leave off the ":" and the "function"
shout() {
console.log("Hi, my name is", this.name);
}
};