28

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>

事件处理程序 buttonClicked 被调用,但 _clickCount 成员不可访问,或者this指向其他对象。

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

4

5 回答 5

40
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');
    }
}

几乎 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`);
   }
}

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

于 2008-10-23T09:33:42.470 回答
12

I don't know why Function.prototype.bind wasn't mentioned here yet. So I'll just leave this here ;)

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');
    }
}
于 2016-03-19T13:00:47.483 回答
8

直接附加到 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'))
于 2008-10-23T10:05:05.307 回答
4

You can use fat-arrow syntax, which binds to the lexical scope of the function

function doIt() {
  this.f = () => {
    console.log("f called ok");
    this.g();
  }
  this.g = () => {
    console.log("g called ok");
  }
}

After that you can try

var n = new doIt();
setTimeout(n.f,1000);

You can try it on babel or if your browser supports ES6 on jsFiddle.

Unfortunately the ES6 Class -syntax does not seem to allow creating function lexically binded to this. I personally think it might as well do that. EDIT: There seems to be experimental ES7 feature to allow it.

于 2016-03-19T16:22:21.983 回答
0

I like to use unnamed functions, just implemented a navigation Class which handles this correctly:

this.navToggle.addEventListener('click', () => this.toggleNav() );

then this.toggleNav() can be just a function in the Class.

I know I used to call a named function but it can be any code you put in between like this :

this.navToggle.addEventListener('click', () => { [any code] } );

Because of the arrow you pass the this instance and can use it there.

Pawel had a little different convention but I think its better to use functions because the naming conventions for Classes and Methods in it is the way to go :-)

于 2021-01-08T16:55:05.657 回答