如何在jQuery事件函数中访问对象属性

Mar*_*tMS 5 javascript jquery

对不起我的英语不好.这是示例代码:

/**
 * @constructor
 */
function MyNewClass(){
  this.$my_new_button = $('<button>Button</button>');
  this.my_value = 5;

  this.init = function (){
    $('body').append(this.$my_new_button);
    this.$my_new_button.click(
      function (){
        // Its always alerts "undefined"
        alert(this.my_value);
      }
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

如何my_value在jQuery click事件函数中访问对象属性?可能吗?

Ben*_*enM 6

您可以执行以下操作

function MyNewClass(){
    this.$my_new_button = $('<button>Button</button>');
    this.my_value = 5;
    var self = this; //add in a reference to this
    this.init = function (){
        $('body').append(this.$my_new_button);
        this.$my_new_button.click(
            function (){
                //This will now alert 5.
                alert(self.my_value);
            }
        );
    };
}
Run Code Online (Sandbox Code Playgroud)

这是javascript中的一个小模式(虽然这个名字不包括我).它允许您在内部函数中访问函数的顶级成员.在嵌套函数中,您不能使用"this"来引用顶级成员,因为它只会引用您所在的函数.因此需要将顶级函数"this"值声明为自己的变量(在本例中称为self).