13

Alright, so I have two classes. Class 1 contains a specific function, which accesses some of the class' properties. This is what it looks like:

function class1() {
    this.variable = "something";
}

class1.prototype.callback = function() {
    console.log(this.variable); // Returns undefined
}

Class 2 can call any function it is given, and looks like this:

function class2() {}

class2.prototype.caller = function(callback) {
    callback();
}

Then in my regular Javascript I do this:

var c1 = new class1();
var c2 = new class2();
c2.caller(c1.callback);

It is supposed to return "something", however it throws an undefined error. I know it is because it is in the scope of class2 and it is trying to access the variable there, however I have no idea how to get it to execute within the scope of class1.

Any help is greatly appreciated!

Qub1
  • 1,154
  • 2
  • 14
  • 31

1 Answers1

16

Use .bind() or a wrapper function:

c2.caller(c1.callback.bind(c1));

Note that your code was wrong in that it called the function before passing in the return value.

Alternatively:

c2.caller(function() { c1.callback(); });
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Ah yes I see, I made a mistake typing this. I'm going to try bind, thanks! – Qub1 Dec 01 '14 at 17:00
  • @Qub1 the only issue with `.bind()` is that it's not supported in really old browsers, but [a fill-in is available at the MDN site.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill) – Pointy Dec 01 '14 at 17:04