类方法作为JavaScript中的事件处理程序?

Jac*_*obE 21 html javascript class function

JavaScript中是否有最佳实践或常用方法将类成员作为事件处理程序?

考虑以下简单示例:

<head>
    <script language="javascript" type="text/javascript">

        ClickCounter = function(buttonId) {
            this._clickCount = 0;
            document.getElementById(buttonId).onclick = this.buttonClicked;
        }

        ClickCounter.prototype = {
            buttonClicked: function() {
                this._clickCount++;
                alert('the button was clicked ' + this._clickCount + ' times');
            }
        }

    </script>
</head>
<body>
    <input type="button" id="btn1" value="Click me" />
    <script language="javascript" type="text/javascript">
        var btn1counter = new ClickCounter('btn1');
    </script>
</body>
Run Code Online (Sandbox Code Playgroud)

事件处理程序buttonClicked被调用,但_clickCount成员不可访问,或指出了一些其他对象.

关于这类问题的任何好的提示/文章/资源?

paw*_*wel 25

ClickCounter = function(buttonId) {
    this._clickCount = 0;
    var that = this;
    document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };
}

ClickCounter.prototype = {
    buttonClicked: function() {
        this._clickCount++;
        alert('the button was clicked ' + this._clickCount + ' times');
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑差不多10年后,使用ES6,箭头功能和类属性

class ClickCounter  {
   count = 0;
   constructor( buttonId ){
      document.getElementById(buttonId)
          .addEventListener( "click", this.buttonClicked );
  }
   buttonClicked = e => {
     this.count += 1;
     console.log(`clicked ${this.count} times`);
   }
}
Run Code Online (Sandbox Code Playgroud)

https://codepen.io/anon/pen/zaYvqq

  • 这是一个很好的例子,但是这个答案可能会更好一些解释为什么它是一个很好的解决方案,对于这里的新手. (8认同)

Ant*_*nes 7

直接附加到onclick属性的函数将具有this指向元素的执行上下文属性.

当你需要一个元素事件来对象的特定实例(在.NET中作为委托)运行时,你需要一个闭包: -

function MyClass() {this.count = 0;}
MyClass.prototype.onclickHandler = function(target)
{
   // use target when you need values from the object that had the handler attached
   this.count++;
}
MyClass.prototype.attachOnclick = function(elem)
{
    var self = this;
    elem.onclick = function() {self.onclickHandler(this); }
    elem = null; //prevents memleak
}

var o = new MyClass();
o.attachOnclick(document.getElementById('divThing'))
Run Code Online (Sandbox Code Playgroud)


kuc*_*ova 5

我不知道为什么Function.prototype.bind这里没有提到。所以我就把这个留在这里;)

ClickCounter = function(buttonId) {
    this._clickCount = 0;
    document.getElementById(buttonId).onclick = this.buttonClicked.bind(this);
}

ClickCounter.prototype = {
    buttonClicked: function() {
        this._clickCount++;
        alert('the button was clicked ' + this._clickCount + ' times');
    }
}
Run Code Online (Sandbox Code Playgroud)


Ter*_*nen 5

您可以使用粗箭头语法,它绑定到函数的词法范围

function doIt() {
  this.f = () => {
    console.log("f called ok");
    this.g();
  }
  this.g = () => {
    console.log("g called ok");
  }
}
Run Code Online (Sandbox Code Playgroud)

之后你可以尝试

var n = new doIt();
setTimeout(n.f,1000);
Run Code Online (Sandbox Code Playgroud)

你可以在babel上尝试一下,或者如果你的浏览器支持jsFiddle上的 ES6 的话。

不幸的是,ES6 Class 语法似乎不允许创建词法绑定到 this 的函数。我个人认为也可以这样做。编辑:似乎有实验性的 ES7 功能允许它