javascript scope issue
开发者_JS百科Code snippet as follows:
$(this).parents('td:first').next().find('option').customizeMenu('myMenu2');
This works,but :
var listener = function(){
$(this).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener();
is not working,why and how to fix it?
'this' does not point to the same object when put in a function, it points to the current function (in your case 'listener'). Take it as a parameter instead, if that is an option (it depends on how you call your function).
var listener = function(obj){
$(obj).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener(this);
this
is the function. Try:
var listener = function(element){
$(element).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener(this);
精彩评论