我需要创建一个至少有两个方法的对象。第一个方法创建一个事件,将按钮绑定(bind)到对象的第二个方法。
但是,我在创建事件时遇到了问题。 this
一直附加到按钮而不是对象的实例。
我试过 bind()
但如果它是解决方案,我没有找到使用它的好方法。
这有可能吗?如果是,如何实现?
function obj()
{
this.attribute = 42;
this.eventer();
}
obj.prototype.eventer = function()
{
$("#but").on("click",this.print);
}
obj.prototype.print = function()
{
$("#print").html(this.attribute);
}
var test = new obj();
<script src='//code.jquery.com/jquery.min.js'></script>
<button id="but">Click me !</button>
<div id="print"></div>
最佳答案
来自 bind() 的 javascript 引用手册:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
将处理程序传递给点击事件时,只需使用 this.print.bind(this)
。
function obj()
{
this.attribute = 42;
this.eventer();
}
obj.prototype.eventer = function()
{
$("#but").on("click",this.print.bind(this));
}
obj.prototype.print = function()
{
$("#print").html(this.attribute);
}
var test = new obj();
<script src='//code.jquery.com/jquery.min.js'></script>
<button id="but">Click me !</button>
<div id="print"></div>
关于javascript - 添加事件调用其他方法的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48304869/