Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass class function as parameter to another class to use as callback in JavaScript [duplicate]

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!

like image 280
Qub1 Avatar asked Dec 01 '14 15:12

Qub1


People also ask

How do you pass a callback function in JavaScript?

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.

Can callback functions have parameters?

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.

Can we pass function as a parameter in JavaScript?

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.

What are the parameters passed to a callback?

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.


1 Answers

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(); });
like image 121
Pointy Avatar answered Oct 13 '22 00:10

Pointy