为什么这个私有方法在构造函数中

why is this private method in a constructor?

本文关键字:构造函数 有方法 为什么      更新时间:2023-09-26

我对我遇到的这种编码模式有点困惑,即使我一直在研究'这个'。以下(简化)代码显示了该模式:

var MyConstructor = function MyConstructor() {
    this._handlers = {
        action: this.handleAction.bind(this)
    };
};
MyConstructor.prototype.start = function(someObj) {
    this.someObj.on(’some event’, this._handlers.action);  //<--here
}
MyConstructor.prototype.handleAction = function() {
    //do stuff
}
module.exports = MyConstructor;

我的问题是,为什么构造函数中需要私有方法?这种模式是否避免了一些常见问题?是否可以简单地评论//<--here

this.someObj.on(’some event’, this.handleAction);

不,它们是不同的。区别在于上下文,这意味着函数中this的值。

this.handleAction将函数传递给on,没有任何上下文。没有指定this值。该值将在执行函数时确定。该值很可能不是MyConstructor对象,因此this.start例如,不会引用正确的对象,或者实际上根本不会引用任何对象。

解决方案是bind上下文。这将永远设置上下文,因此this将始终引用正确的值。您会看到以下代码行:

action: this.handleAction.bind(this)

这意味着,当代码稍后引用 this._handlers.action 时,它将使用适当的上下文将函数发送到on,因此this将始终指向正确的值。

以下几行之间的差异

this.someObj.on(’some event’, this.handleAction.bind(this));
this.someObj.on(’some event’, this.handleAction);

。是第一个handleAction将运行,这是MyConstructor的实例,而第二个将在事件处理机制决定的任何上下文中运行。如果它是这样的,它将运行,这是全局对象:

function on (a, callback) {
  callback(); // callback is run with this as the global object 
              // UNLESS it was bound to something else
}

"private"_handlers属性只是一个对象,它包含对绑定到实例的回调的引用。如果要调用 bind 两次,将创建两个函数。_handlers 属性可以创建单个绑定函数,该函数可用作任意数量的事件的处理程序。