Sakib
Sakib

Reputation: 1543

javascript passing a function in a class that needs another function from that class object

I am passing a function in a class or var object as an argument to another function. The function that takes in the function from the class executes that function. It would work fine, however the function of the class calls another function from the class. The console outputs the error that the function being called in the class function is undefined.

The following might illustrate a bit better

//the class variable in someClass.js
function(params...){
  getSomethingInClass: function(){
     // return some variable
  }

  functionThatIsPassed: function(arg){
    var theCalledFunction = getSomethingInClass();
    //do something with theCalledFunction
  }
}

//SOME WHERE ELSE in another function in another file
OtherFunction: function(){
//someClass is a variable being used here
  FunctionThatTakesFunction(this.someClassVar.functionThatIsPassed);
}


//FunctionThatTakesFunction is implemented in another file
FunctionThatTakesFunction(callbackFun){
  callbackFun(someArg);
}

The above will work if I change it to pass the entire object someClass object. That is bad programming practice to pass the object because FunctionThatTakesFunction needs to know the functions of its argument For example

//THIS WORKS!
//other stuff is same 

//SOME WHERE ELSE in another function in another file
OtherFunction: function(){
//someClass is a variable being used here
  FunctionThatTakesFunction(this.someClassVar);
}


//FunctionThatTakesFunction is implemented in another file
FunctionThatTakesFunction(object){
  object.functionThatIsPassed(someArg);
}

Upvotes: 4

Views: 12489

Answers (2)

Rykad
Rykad

Reputation: 21

I use Closures:

class Sample() {
    constructor() {
        this.id = 'Sample';
    }

    method(text) {
        console.log(this.id + text)
    }

    getMethod() {
        const ref = this;
        return function(text) {
            ref.method(text);
        }
    }
}

Elsewhere:

someFunc() {
    const sample = new Sample();
    useFunc(sample.getMethod());
}

useFunc(func) {
    func('HI');
}

Output: SampleHI

Upvotes: 0

Jackson Ray Hamilton
Jackson Ray Hamilton

Reputation: 9466

Here are some examples of passing a function into another function: (Fiddle here: http://jsfiddle.net/FvyUQ/4/)

function Cat() {
  this.myMeow = 'Mrrow';

  this.scratch = function() {
    console.log('Scritchey-scratch.');
  }
}

Cat.prototype.meow = function() {
  console.log(this.myMeow);
}

Cat.prototype.jump = function() {
  console.log('The cat jumped and said ' + this.myMeow + '!');
}

function test(fn) {
  fn();
}

function callPrototype(fn, context) {
  fn.call(context);
}

var myCat = new Cat();

test(myCat.scratch);
test(myCat.meow);
test(myCat.jump);
test(Cat.prototype.jump);
callPrototype(Cat.prototype.jump, myCat);

Upvotes: 2

Related Questions