开发者

How to make a super in javascript function

开发者 https://www.devze.com 2023-03-18 15:48 出处:网络
Like in this example: var teste = {name:\'marcos\'}; $(teste).each(function(){ var name = this.name; // i don\'t want to do that.

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 somethi开发者_JAVA百科ng like "super" in java? or similar way to do?
    }
    sayName();

});

How can i do that?


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


I saw a lot of examples on Internet (jQuery-based including) using this:

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


Here is yet another way:

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

var that = this;

var sayName = function(){
    alert(that.name);
}
sayName();

});

That is your super :-) Seriously, there is no "super" because it's not extension.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号