Javascript对象。如何创建在同一对象内调用函数的按钮

Javascript对象。如何创建在同一对象内调用函数的按钮,javascript,object,button,Javascript,Object,Button,我有一个名为“avatar”的JS对象,它有一个创建函数,可以在HTML页面上生成一个按钮并设置一些属性 我想在按钮上设置一个onmouseover,该按钮调用化身对象中的函数,因此我写了: this.create = function(){ this.button = document.createElement("BUTTON"); this.text = document.createTextNode(this.name); this.button.appendCh

我有一个名为“avatar”的JS对象,它有一个创建函数,可以在HTML页面上生成一个按钮并设置一些属性

我想在按钮上设置一个onmouseover,该按钮调用化身对象中的函数,因此我写了:

this.create = function(){
    this.button = document.createElement("BUTTON");
    this.text = document.createTextNode(this.name);
    this.button.appendChild(this.text);
    document.body.appendChild(this.button);
    this.button.style.background=this.color;
    this.button.addEventListener("mouseover", this.randomMove());
}

但是,功能randomMove会立即执行,不会等待鼠标悬停按钮。后续的鼠标指针不起任何作用。

您需要向其传递函数体,而不是函数返回的内容。在您的例子中,代码计算this.randomMove(),并将返回的结果分配给mouseover事件处理程序。它应该是这样的:

this.button.addEventListener("mouseover", this.randomMove);

请看这个简单的示例,以轻松了解发生的情况:

如Andy所述,您需要将函数引用(不带括号)而不是函数表达式(带括号)作为参数传递给addEventListener。

谢谢您的帮助

事实证明,我真正想要的是bind

this.button.addEventListener("mouseover",this.randomMove.bind(this));
这将函数调用绑定到属于此对象的方法。因此,即使生成的HTML不在对象实例的范围内,函数调用也会记住应该调用哪个实例

再次感谢


Ben

this.randomMove
不是
this.randomMove()
。后者立即调用该函数。