Pass class function as parameter to another class to use as callback in JavaScript
class, javascript
Solution
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(); });
Problem
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!