gpt4 book ai didi

javascript - 在 javascript 类中调用类方法

转载 作者:行者123 更新时间:2023-12-02 22:31:45 25 4
gpt4 key购买 nike

这是一个 Vue 类。方法 signOut() 应在计时器计时时触发。计时器工作,除了调用 signOut()

问题在于访问类方法。我对 this、self 和访问修饰符感到困惑。我尝试使用 this.signOut() 但它不起作用。

如何调用方法signOut

"use strict";

(async (globals, config, loader, application) => {

const storageLocal = await loader.services.storage.local.getAsync();

class HeaderComponent {
#foo = a;

constructor(tag) {
this.tag = tag;

this.timer();
}

signOut() {
storageLocal.delete('account');
window.location = '/signin.html';
}

timer() {
//document.getElementById("timer"),
var counter = -1;
var timeout;
var startTimer = function timer() {
counter++;
console.log(counter);

signOut(); //<- error can't call class method
timeout = setTimeout(timer, 10000);
};

function resetTimer() {
// here you reset the timer...
clearTimeout(timeout);
counter = -1;
startTimer();
//... and also you could start again some other action
}

document.addEventListener("mousemove", resetTimer);
document.addEventListener("keypress", resetTimer);
startTimer();
}

data() {
return { account: storageLocal.account };
}
}

const component = new HeaderComponent('component-header')
loader.components.set(component.tag, component);

})(window, window.config, window.loader, window.application);

请注意:

        signOut() {
storageLocal.delete('account');
window.location = '/signin.html';
}

timer() {
//document.getElementById("timer"),
var counter = -1;
var timeout;
var startTimer = function timer() {

如您所见,“signOut()”比事件函数低 2 个级别。逻辑上说它会像 this.parent.signOut() 一样工作,但事实并非如此!

EDIT3:this.signOut(); 将产生

Uncaught TypeError: Cannot read property 'signOut' of undefined
at timer (header.js:30)
at HTMLDocument.resetTimer

最佳答案

函数创建一个新的上下文。您需要切换到箭头函数并使用 this.signOut()。简化示例:

  timer() {
var counter = -1;
var timeout;
var startTimer = () => {
counter++;
console.log(counter);

this.signOut();
timeout = setTimeout(startTimer, 1000);
};

setTimeout(startTimer, 1000);
}

此外,您在一个类中定义了两个 signOut() 方法。

关于javascript - 在 javascript 类中调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58877980/

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