lokesh
lokesh

Reputation: 55

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?

Upvotes: 1

Views: 68

Answers (5)

le_m
le_m

Reputation: 20228

// The good:
otherTeamName.getTeamName.call(this);
otherTeamName.getTeamName.apply(this);

// The okayish:
var f = otherTeamName.getTeamName; f();
otherTeamName.getTeamName.bind(this)();

// The bad:
((f) => f)(otherTeamName.getTeamName)();
(function(f) {f()})(otherTeamName.getTeamName)

// The ugly:
eval(otherTeamName.getTeamName)();
eval("(" + otherTeamName.getTeamName + ")()");
new Function("(" + otherTeamName.getTeamName + ")()")();

Upvotes: 0

Quentin
Quentin

Reputation: 943560

Short answer: No. It isn't a property of the object, so you can't access it as if it was.

Longer answer: You could replace the teamName property with a getter function that returned the value of the variable … but that would be an unintuitive approach to whatever the problem is.

Upvotes: 0

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

You can simply use

otherTeamName.getTeamName.call(this)

this here refers to the window

Upvotes: 0

Aloso
Aloso

Reputation: 5397

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

Upvotes: 1

dfsq
dfsq

Reputation: 193261

Yes, you can still use the same getTeamName method by changing context function is executed in:

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

otherTeamName.getTeamName.call(window);

By using Function.prototype.call you make this point to window instead of otherTeamName object.

UPD. However, this will only work if teamName is global variable. If not, check Quentin's answer.

Upvotes: 1

Related Questions