gpt4 book ai didi

javascript - 错误 TypeError : this. setNormal 不是函数 - Angular

转载 作者:行者123 更新时间:2023-11-30 09:17:07 25 4
gpt4 key购买 nike

我正在尝试使用 this 关键字在函数内部调用函数。但是我收到了这样的错误

ERROR TypeError: this.setNormal is not a function

所以根据我的理解,我在内部调用函数的方式可能是错误的原因。请纠正我的方法。

// first function
fun1 (){
setTimeout(function() {
this.setNormal();
}, 2000);
}

// second function
setNormal(){

}

最佳答案

问题在于:

// first function
fun1 (){
setTimeout(function() {
this.setNormal();
}, 2000);
}

// second function
setNormal(){

}

是您定义 this 的方式,因为您使用的是常规 function(){} 语法。如果您阅读了 setTimeout

的规范

Code executed by setTimeout() is called from an execution context separate from the function from which setTimeout was called. The usual rules for setting the this keyword for the called function apply, and if you have not set this in the call or with bind, it will default to the global (or window) object in non–strict mode, or be undefined in strict mode. It will not be the same as the this value for the function that called setTimeout.

我假设您没有在全局范围内定义 setNormal...因此出现了问题。

现在,在 ES6 中,很多人使用 () => {} 函数语法来关闭封闭范围内的 this。

An arrow function does not have its own this. The this value of the enclosing lexical context is used i.e. Arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope they end up finding this from its enclosing scope.

关于javascript - 错误 TypeError : this. setNormal 不是函数 - Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54311670/

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