0

I have 2 js files:

file1.js contains prototype A with:

printname: function() {
   console.log('my name is A');
}

getname: function() {
    console.log('getting name..');
    this.printname();
}

Then I put 'getname' function in a global variable because I want to access it anywhere:

globalvar.myfunction = this.getname;

file2.js contains prototype B with:

runmyglobalfunction: function() {
   globalvar.myfunction();
}

When I call this.runmyglobalfunction, the result is:

I can see console log 'getting name..'.

But I can't see 'my name is A'

How do I fix this?

1 Answers1

1

You can .bind the function's this value to a specific value:

globalvar.myfunction = this.getname.bind(this);

Now, no matter how globalvar.myfunction is called, this inside the function will always refer to what this referred to in that line.

Related: How to access the correct `this` inside a callback?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143