javascript passing a function in a class that needs another function from that class object -
i passing function in class or var object argument function. function takes in function class executes function. work fine, function of class calls function class. console outputs error function being called in class function undefined.
the following might illustrate bit better
//the class variable in someclass.js function(params...){ getsomethinginclass: function(){ // return variable } functionthatispassed: function(arg){ var thecalledfunction = getsomethinginclass(); //do thecalledfunction } } //some else in function in file otherfunction: function(){ //someclass variable being used here functionthattakesfunction(this.someclassvar.functionthatispassed); } //functionthattakesfunction implemented in file functionthattakesfunction(callbackfun){ callbackfun(somearg); }
the above work if change pass entire object someclass object. bad programming practice pass object because functionthattakesfunction needs know functions of argument example
//this works! //other stuff same //some else in function in file otherfunction: function(){ //someclass variable being used here functionthattakesfunction(this.someclassvar); } //functionthattakesfunction implemented in file functionthattakesfunction(object){ object.functionthatispassed(somearg); }
here examples of passing function 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 , 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);
Comments
Post a Comment