How to make super in javascript function

Like in this example:

var teste = {name:'marcos'}; $(teste).each(function(){ var name = this.name; // i don't want to do that. // i want to have access to 'this' inside this function (sayName) var sayName = function(){ alert(name); // there is something like "super" in java? or similar way to do? } sayName(); }); 

How can i do this?

+8
javascript jquery
source share
3 answers

this never implied in JavaScript (as in Java). This means that if you do not call the function as a method for the object, this will not be bound to something reasonable (it will be bound to the window object in the browser). If you want to have this inside a function, this function should be used as a method, that is:

 var teste = {name:'marcos'}; $(teste).each(function(){ this.sayName = function(){ alert(this.name); } this.sayName(); }); 

Then sayName is a method and is called in this

+2
source share

I have seen many examples on the Internet (including jQuery) using this:

 var that = this; var sayName = function() { alert(that.name); } 
0
source share

Here is another way:

 var teste = {name:'marcos'}; $(teste).each(function(){ var that = this; var sayName = function(){ alert(that.name); } sayName(); }); 

This is your super :-) Seriously, there is no "super" because it is not an extension.

-one
source share

All Articles