Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 349
Sakib Avatar asked Sep 20 '26 17:09

Sakib


1 Answers

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);
like image 51
Jackson Avatar answered Sep 23 '26 08:09

Jackson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!