且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JavaScript中创建类onclick的新实例的正确方法是什么?

更新时间:2023-02-09 17:01:00

obj.setup.bind(obj)将上下文绑定到函数,但未调用它.您要么需要调用它:

obj.setup.bind(obj) binds a context to a function, but it does not call it. You either need to call it:

obj.setup.bind(obj)();

或使用 .call()代替 .bind():

obj.setup.call(obj);

但是,在这种情况下,由于直接在实例上调用该方法,因此实际上不需要绑定任何东西:

However in this case, since you call the method directly on the instance, there is not really a need to bind anything:

$(document).ready(function() {
  var $ = document.getElementById.bind(document); // <-- bind without calling
  
  class someClass {
    constructor() {
      this.ready = false;
    }
    setup() {
      this.ready = true;
    }
  }

  $('startButton').addEventListener('click', function(event) {
      var obj = new someClass();
      obj.setup();
      console.log(obj.ready); // true
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="startButton">Start</button>