2013-09-25 35 views
5

对不起,我的英语。下面是示例代码:如何访问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 my_value物业单击事件函数? 这可能吗?

回答

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的一个小图案(虽然名字我摸不透)。它允许您在内部函数中访问函数的顶层成员。在嵌套函数中,您不能使用“this”来引用顶层成员,因为它只会引用您所在的函数。因此需要将顶级函数“this”的值声明为它自己的变量(在这种情况下称为self)。

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