Javascript: passing function parameters vs using variables from the closure -
suppose have helper function logs info methods called ,
obj = function(){}; obj.prototype.run = function(f /*, ...*/){ var args = array.prototype.slice.call(arguments, 1); console.log("called function " + f.name + " arguments", args); f.apply(this, args); }; now suppose want write method accepts single parameter x , simplicity prints out. have next options:
option 1: create method delegate functionality "hidden" method "does real job":
obj.prototype.method1 = function(x){ this.run(this.__method1__, x); }; obj.prototype.__method1__ = function a(x){ console.log(x); }; option 2: same, without creating sec method
obj.prototype.method2 = function(x){ this.run( function b(x){ console.log(x); }, x); }; option 3: same method 2, not pass x parameter, inheriting closure instead.
obj.prototype.method3 = function(x){ this.run( function c(){ console.log(x); }); }; which method more efficient in terms of speed or memory? in particular, in options 2 , 3 anonymous function recreated each time method called?
javascript closures
No comments:
Post a Comment