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

How to access to object property inside jQuery event function

本文关键字:函数 对象 属性 事件 jQuery 何访问 访问      更新时间:2023-09-26

对不起我的英语。下面是示例代码:

/**
 * @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);
      }
    )
  }
}

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

您可以执行以下操作

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);
            }
        );
    };
}

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

Jquery有一个方法,jQuery.proxy(函数,上下文):

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(
      $.proxy(function (){
        // Its always alerts "undefined"
        alert(this.my_value);
      },this)
    )
  }
}

演示