Javascript 如何从node.js中的函数调用结构内部的函数?
好的,这是我代码的基本概要Javascript 如何从node.js中的函数调用结构内部的函数?,javascript,node.js,Javascript,Node.js,好的,这是我代码的基本概要 exports.entity = { name:"Foo", //Etc... start:function() { this.attack(); }, attack:function() { setTimeout(attack, 1000); //Doesn't work setTimeout(this.attack, 1000); //Doesn't work
exports.entity = {
name:"Foo",
//Etc...
start:function() {
this.attack();
},
attack:function() {
setTimeout(attack, 1000); //Doesn't work
setTimeout(this.attack, 1000); //Doesn't work
setTimeout(this, 1000); //Doesn't work
}
}
正如您可能看到的,我想使用setTimeout
从该函数内部调用attack()
。不幸的是,我尝试过的一切都不起作用,我的想法也越来越少。我在网上找不到任何东西。有人知道我怎样才能做到这一点吗
注:
当我说
不起作用时,我的意思是它给了我一个错误,比如说(插入我在这里尝试过的东西,例如“this.attack”)不是一个函数
为了避免范围问题,我通常做的是分割函数。然后导出对象
const attack = () => {
console.log('attacking');
setTimeout(() => {
stop();
}, 1000)
};
const stop = () => {
console.log('stopping');
}
const start = () => {
attack();
}
module.exports = { start, stop, attack }
否则,您可以按照注释中的建议绑定(此)。setTimeout
有自己的作用域,这就是它覆盖此的原因
您可以使用bind
或在setTimeout
//using bind
setTimeout((function() {
this.attack();
}).bind(this));
//using variable
var context = this;
setTimeout(context.attack, 1000);
它可以是这样的:
let entity = {};
entity.name = "Foo";
// Etc...
entity.start = function() {
this.attack();
}.bind(entity);
entity.attack = function() {
console.log('attack');
setTimeout(this.attack, 1000); //Doesn't work
}.bind(entity);
exports = { entity };
setTimeout(()=>this.attack(),…)
或setTimeout(this.attack.bind(this),…)
或attack:function-attack(){setTimeout(attack,1000);}
感谢Patrick Roberts,这很有效。