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

时间:2013-09-25 12:20:41

标签: 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);
      }
    )
  }
}

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

2 个答案:

答案 0 :(得分: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);
            }
        );
    };
}

这是javascript中的一个小模式(虽然这个名字不包括我)。它允许您在内部函数中访问函数的顶级成员。在嵌套功能中,您无法使用&#34;这个&#34;引用顶级成员,因为它只会引用您所在的功能。因此需要申报顶层功能&#34;这个&#34;将值转换为自己的变量(在本例中称为self)。

答案 1 :(得分:4)

Jquery有一个方法,jQuery.proxy( function, context )

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

DEMO

相关问题