var std_obj = {
activeEffect : 'fade',
name : 'Jane',
displayMe() {
const doSomeEffects = () => {
if (this.activeEffect === 'fade') {
console.log(this.name); // this.name have accesss and logs
// return this.name --> gives undefined ? why can't I return?
}
};
doSomeEffects();
}
};
console.log(std_obj.displayMe());
//console.log(this.name) 有效,但我无法返回 this.name,我有点沮丧
最佳答案
箭头函数将采用其声明范围的 this
。这就是为什么这里的 this
会指向对象。但是要查看该值,您必须像这样更改代码:
var std_obj = {
activeEffect : 'fade',
name : 'Jane',
displayMe() {
const doSomeEffects = () => {
if (this.activeEffect === 'fade') {
console.log(this.name); // this.name have accesss and logs
return this.name; //uncomment this
}
};
return doSomeEffects(); //if you do not use return statement, then it will by default return undefined
}
};
console.log(std_obj.displayMe());
如果您不从 displayMe() 或 doSomeEffects() 返回任何内容,它就不会显示 undefined
。原因是函数默认返回 undefined
。要对此进行测试:只需在开发控制台中运行 console.log("hello");
。这将显示 hello 和 undefined。
注意:如果你使用函数表达式而不是箭头函数,它会返回undefined。这就是箭头函数的强大之处。
关于javascript - 这不返回对象属性(箭头,this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67798897/