gpt4 book ai didi

javascript - 对象函数内的作用域?

转载 作者:行者123 更新时间:2023-12-03 01:48:33 27 4
gpt4 key购买 nike

“this”在 logColor 函数内提供 myCar 对象引用,但在 func 函数内提供 window 对象引用,为什么?

var myCar = {
color: "Blue",
logColor: function() {
var self = this;
console.log("In logColor - this.color: " + this.color);
console.log("In logColor - self.color: " + self.color);
var func=function() {
console.log("In IIFE - this.color: " + this.color);
console.log("In IIFE - self.color: " + self.color);
}
func();
}
};

myCar.logColor();

对于专业的 javascript 开发人员来说,这可能没有意义,但我的基础知识已经动摇了

最佳答案

您可以使用ES-6 Fat Arrow Notation来完成您的任务。发生这种情况是因为对象的闭包内 this 始终指向全局范围。

var myCar = {
color: "Blue",
logColor: function() {
var self = this;
console.log("In logColor - this.color: " + this.color);
console.log("In logColor - self.color: " + self.color);
var func=() => {
console.log("In IIFE - this.color: " + this.color);
console.log("In IIFE - self.color: " + self.color);
}
func();
}
}

关于javascript - 对象函数内的作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50520478/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com