JavaScript 单例方法上的 _.bindAll() ?

发布于 2024-12-12 12:52:51 字数 527 浏览 5 评论 0原文

下面代码中的方法 obj2.method1 是从另一个对象调用的。 如何绑定“this context”以便我可以从 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();

谢谢:)

The method obj2.method1, in the code below, is called from another object.
How do I bind the "this context" so that I can refer to obj1 from obj2?

var singleton = {
  obj1 : {
     a : 5
  },

  obj2 : {
    method1 : function(){
       this.obj1.a; //undefined
    }
  }
}

I tried using underscore _.bindAll() - something along these lines - but failed ...

var singleton = {
  obj1 : {
     a : 5
  },

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

singleton.init();

Thanks :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘你却要生生世世 2024-12-19 12:52:51
  1. 您需要使用 _.bind() 的结果重新分配 singleton.obj2.method2()

    // 在 .init() 中:

    this.obj2.method1 = _.bind(this.obj2.method1, this)

  2. To singleton.init() 在调用时有一个正确的 this,您需要显式指定它:

    singleton.init.call(singleton)

完整演示此处。但请记住,Singleton 模式 < a href="http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/" rel="nofollow">不好,我可以吗?

  1. You need to reassign singleton.obj2.method2() with the results of _.bind():

    // in .init():

    this.obj2.method1 = _.bind(this.obj2.method1, this)

  2. To have singleton.init() have a proper this when called, you need to specify it explicitly:

    singleton.init.call(singleton)

Full demonstration here. But remember, the Singleton pattern is bad, m'kay?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文