class Lock {
#flag = false;
#delayTime = 0;
#callback = null;
constructor(callback, delayTime = 0) {
if (typeof callback !== "function") {
throw new Error("callback must be a function");
}
if (typeof delayTime !== "number") {
throw new Error("delayTime must be a number");
}
this.#flag = false;
this.#callback = callback;
this.#delayTime = delayTime;
}
lock() {
this.#flag = true;
}
unlock() {
setTimeout(() => {
this.#flag = false;
}, this.#delayTime);
}
async run() {
if (this.#flag) return;
this.lock();
let result = await this.#callback();
this.unlock();
return result;
}
}
/**
* 执行回调函数
* @param callback
*/
function RunFunc(callback) {
callback();
}
let lock = new Lock(function () {
console.log(111);
}, 50);
lock.run();
当调用lock.run
时,此时lock
内部的this
指向就是该函数本身Lock
,正常输出111
执行下面的函数
RunFunc(lock.run);
RunFunc
的this
指向window
,所以传过来的lock.run
的this
也被改变为this
,此时RuncFunc
内调用lock.run
时会报错TypeError: Cannot read properties of undefined (reading '#flag')
解决方法
使用下面的方式传递即可解决
RunFunc(() => {
lock.run();
});
RunFunc(function () {
lock.run();
});