gpt4 book ai didi

javascript - 严格模式回调中访问公共(public)值

转载 作者:行者123 更新时间:2023-11-29 23:21:21 25 4
gpt4 key购买 nike

我在这样的回调中访问了公共(public)值。

function InfoClass() {
var local = 1;
self = this;
}
InfoClass.prototype.myFunction = function (){
this.win.addEventListener('open', function(e){
// I can't use 'this' here.
self.local // So I access common value in callback like this.
});
}

在严格模式之前它起作用,

但是,现在我需要设置严格模式,所以它显示错误 self doesn't have var

还有其他方法吗??

最佳答案

你可以试试看

InfoClass.prototype.myFunction = function (){
var self = this;
this.win.addEventListener('open', function(e){
self.local // you can access the function now
});
}

或者你可以像下面这样使用箭头函数

InfoClass.prototype.myFunction = function (){
this.win.addEventListener("open", (e) => {
this.local // you can use this now
});
}

供引用,Arrow functions

关于javascript - 严格模式回调中访问公共(public)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50480077/

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