gpt4 book ai didi

javascript - 公共(public)变量在私有(private)方法中返回未定义

转载 作者:行者123 更新时间:2023-11-28 19:41:34 25 4
gpt4 key购买 nike

我有一段非常简单的代码,我的问题是:为什么变量 this.wheelsgetWheel() 私有(private)方法中未定义?我确实通过将上下文作为公共(public) this.spinWheel() 方法内的调用中的参数传递来解决了这个问题(编写 getWheel.call(this,wheelNumber)),但是这只是我读完一篇文章后拍摄的,我不太确定我在做什么,因为这篇文章不太好。

我知道这是函数获取错误上下文的原因,但我就是无法理解它(如果私有(private)函数位于Car)内,为什么它没有获取正确的上下文>?)。有人可以详细解释或提供好的资源来阅读吗?

JavaScript:

Car = function () {

this.wheels = [1, 2, 3, 4];

function getWheel (wheel) {
this.wheels.some(function (element, index, array) {
if (element == wheel) {
document.getElementById("text").innerHTML = "Wheel " + element + ": vruuum!";
}
});
};

this.spinWheel = function (wheelNumber) {
getWheel(wheelNumber);
};

};

var myCar = new Car();

myCar.spinWheel();

代码是in this JsFiddle .

欢迎任何其他建议,提前致谢!

最佳答案

那是因为您没有在正确的上下文中调用它。

如果添加

console.log(this)

getWheel的开头,您会看到thiswindow,即非严格模式下的全局默认上下文。

解决方案是改变

this.spinWheel = function (wheelNumber) {
getWheel(wheelNumber);
};

this.spinWheel = function (wheelNumber) {
getWheel.call(this, wheelNumber);
};

您还可以在构造函数中声明一个包含 this 的变量并直接使用它,或者将 this.wheels 存储在私有(private)变量中。

关于javascript - 公共(public)变量在私有(private)方法中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24918671/

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