Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a 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 that?

like image 385
tiagomac Avatar asked Jul 06 '11 13:07

tiagomac


1 Answers

this is never implicit in JavaScript (as it is in Java). This means that if you do not invoke a function as a method on an 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 a this inside the function, that 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 invoked in this

like image 191
Mathias Schwarz Avatar answered Oct 20 '22 01:10

Mathias Schwarz