_.bindAll()用于JavaScript单例方法

_.bindAll() on JavaScript singleton methods?

本文关键字:JavaScript 单例 方法 用于 bindAll      更新时间:2023-09-26

方法obj2。在下面的代码中,Method1是从另一个对象调用的。我如何绑定"此上下文",以便我可以从obj2引用obj1 ?

var singleton = {
  obj1 : {
     a : 5
  },
  obj2 : {
    method1 : function(){
       this.obj1.a; //undefined
    }
  }
}

我尝试使用下划线_.bindAll() -沿着这些行-但失败了…

var singleton = {
  obj1 : {
     a : 5
  },
  obj2 : {
    method1 : function(){
       this.obj1.a; //undefined
    }
  },
  init : function(){
       _.bind(this, obj2.method1)
  }
}
singleton.init();

谢谢:)

  1. 您需要用_.bind()的结果重新分配 singleton.obj2.method2():

    //in .init():

    this.obj2。Method1 = __bind (this.obj2. bind)method1,这)

  2. 要使singleton.init()在调用时具有适当的this,您需要显式指定它:

    singleton.init.call (singleton)

完整的演示在这里。但记住,Singleton模式很糟糕,好吗?