获取未定义的对象方法
Getting an undefined in object method
为什么我得到 undefined
?所以我认为这是箭头函数内部的问题......
我需要通过方法 say
中的箭头函数让它工作
const obj = {
a: 42,
say: () => {
console.log(this.a);
}
};
obj.say();
不要使用箭头函数,因为它们没有自己的 this
。因此,this
(在箭头函数的情况下)将指向封闭上下文。
var obj = {
a: 42,
say: function() {
console.log(this.a);
}
};
obj.say();
正如其他答案所解释的那样,Arrow Functions 没有 this
值。
如果你想要类似的简洁语法,你可能想尝试 ES6 Method Definition 语法,它确实有 this
个值,并且比整个 function(){...}
更短
var obj = {
a: 42,
say() {
console.log(this.a);
}
}
如果您要像这样构建您的应用程序,那么全力以赴并使用 ES6 Classes。
可能是有意义的
顺便说一句,您显然也可以执行以下操作:
var obj = {
a: 42,
say() {
console.log(obj.a); //obj not this
}
}
为什么我得到 undefined
?所以我认为这是箭头函数内部的问题......
我需要通过方法 say
const obj = {
a: 42,
say: () => {
console.log(this.a);
}
};
obj.say();
不要使用箭头函数,因为它们没有自己的 this
。因此,this
(在箭头函数的情况下)将指向封闭上下文。
var obj = {
a: 42,
say: function() {
console.log(this.a);
}
};
obj.say();
正如其他答案所解释的那样,Arrow Functions 没有 this
值。
如果你想要类似的简洁语法,你可能想尝试 ES6 Method Definition 语法,它确实有 this
个值,并且比整个 function(){...}
var obj = {
a: 42,
say() {
console.log(this.a);
}
}
如果您要像这样构建您的应用程序,那么全力以赴并使用 ES6 Classes。
可能是有意义的顺便说一句,您显然也可以执行以下操作:
var obj = {
a: 42,
say() {
console.log(obj.a); //obj not this
}
}