user198729
user198729

Reputation: 63626

javascript scope issue

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?

Upvotes: 0

Views: 94

Answers (2)

Kobi
Kobi

Reputation: 137997

this is the function. Try:

var listener = function(element){
  $(element).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener(this);

Upvotes: 3

Björn
Björn

Reputation: 29381

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

Upvotes: 6

Related Questions