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!
Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn); Above is an example of a callback variable in JavaScript function.
forEach() method as an example, the callback function will always receive the current item, its index, and the array itself as arguments, in that order. You can name the parameters for them anything you want, or even omit them entirely, but the method will always pass them in as arguments.
Passing a function as an argument to the function is quite similar to the passing variable as an argument to the function. so variables can be returned from a function. The below examples describe passing a function as a parameter to another function.
A callback function, also known as a higher-order function, is a function that is passed to another function (let's call this other function “otherFunction”) as a parameter, and the callback function is called (executed) inside the other function.
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With