admin管理员组文章数量:1356908
Sorry for my english. Here is example code:
/**
* @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);
}
)
}
}
How can i access objects my_value
property inside jQuery click event function?
Is it possible?
Sorry for my english. Here is example code:
/**
* @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);
}
)
}
}
How can i access objects my_value
property inside jQuery click event function?
Is it possible?
2 Answers
Reset to default 6You can do the following
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);
}
);
};
}
This is a small pattern in javascript (although the name eludes me). It allows you to access top level members of a function within an inner function. In a nested function you can't use "this" to refer to top level members as it will only refer to the function you are within. hence the need to declare the top level functions "this" value into its own variable (called self in this case).
Jquery has a method for that, 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
本文标签: javascriptHow to access to object property inside jQuery event functionStack Overflow
版权声明:本文标题:javascript - How to access to object property inside jQuery event function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743999249a2573554.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论