【问题标题】:jQuery binding inside JavaScript objectJavaScript 对象内的 jQuery 绑定
【发布时间】:2014-07-20 10:01:49
【问题描述】:

假设我有一个结构如下的对象:

var obj = {
   prop1: "val",
   init: function(){
       this.bindings();
   },
   bindings: function(){
     $(".some-class").on('click', this.someFunction);
   },
   someFunction(){
     this.prop1--; // this does not refer to the right scope
     console.log(this); //logs $(".some-class")[0] object
   }
}

如果在someFunction 中我希望上下文是obj 而不是$(".some-class")[0] 对象怎么办?

目前,我正在使用这个解决方案:

$(".some-class").on('click', $.proxy(this.someFunction, this));

它正在工作,但我在问自己是否有更好/优雅的方法来解决这个问题。

【问题讨论】:

  • this.someFunction.bind(this) MDN bind
  • jQuery 覆盖了这个,所以你可以使用 jQuery.proxy() 之类的东西,或者只是做一些聪明的 var self=this 并使用 self 代替 this
  • var self = this 之类的东西不会改变 function 的执行范围
  • @epascarello 谢谢,不知道。

标签: javascript jquery scope


【解决方案1】:
var obj = {
    prop1: "val",
    init: function(){
        this.bindings();
    },
    bindings: function(){
        var self = this;
        $(".some-class").on('click', function(){
            self.someFunction();
        });
    },
    someFunction: function(){
        this.prop1--; // this does not refer to the right scope
        console.log(this); //logs $(".some-class")[0] object
    }
};

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 2014-02-18
    • 2023-03-26
    • 2010-12-29
    • 1970-01-01
    • 2019-09-29
    • 2016-04-23
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多