javascript - 添加事件调用其他方法的方法

标签 javascript events methods this

我需要创建一个至少有两个方法的对象。第一个方法创建一个事件,将按钮绑定(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/

相关文章:

Python装饰器和类方法及求值——django memoize

java - 尝试在方法内调用方法

java - 将方法参数传递给java中byte,int,int类型的方法参数

javascript:限制项目数

javascript - XMLHttpRequest responseText 在 Firefox WebExtension 中始终为空

c# - 在 DataGridView 中编辑单元格后,我应该在哪个事件之后执行操作?

java - 与在 Java 中使用 Swing 创建 GUI 相关

javascript - 如何使用 Javascript 捕捉 youtube 视频播放器的播放/暂停事件?

javascript - Node.JS 大端 UCS-2

javascript - 如果 Array 键实际上是字符串,那么 Array 与 Object 的区别是什么?