lokesh lokesh - 4 months ago 8
Javascript Question

Javascript : can we reuse inner function to acces both global and local

var teamName ="studio";
var otherTeamName ={
teamName :'factory',
getTeamName : function(){
alert(this.teamName);
}
};
window.otherTeamName.getTeamName();// alerts factory


Is there any way to get the
studio
? by using the same
getTeamName
function.(i.e i know, removing
this
will fetch studio.) without removing the this?

Answer

Yes, it is possible. There are two ways:

  1. use call: otherTeamName.getTeamName.call(window)
  2. copy reference:

    var getTeamName = otherTeamName.getTeamName;
    getTeamName(); // alerts studio
    

call() is not supported by older browsers, the second solution works everywhere.

var teamName = "studio";

var otherTeamName = {
    teamName: 'factory',
    getTeamName: function() {
        alert(this.teamName);
    }
};
otherTeamName.getTeamName(); // alerts factory

var getTeamName = otherTeamName.getTeamName;
getTeamName(); // alerts studio

Comments