javascript - How can rewrite function instead of reference? -


var bigobject = (function() {    function deepcalculate(a, b, c) {     return + b + c;   }    function calculate(x) {     deepcalculate(x, x, x);   }    return {     calculate: calculate,     api: {               deepcalculate: deepcalculate     }   } })(); 

this basic self executing function private function keep in api. problem have can't overwrite deepcalculate outside of function.

how problem? use jasmine , want test if function called. example:

spyon(bigobject, 'calculate').andcallthrough(); expect(bigobject.api.deepcalculate).tohavebeencalled(); 

fails. debug, sure jasmine binds bigobject.api.deepcalculate spy, inside calculate still calls original deepcalculate function , not spy.

i know how can overwrite function , not reference it.

the simple answer be:

(function () {     var overwriteme = function(foo)     {         return foo++;     },     overwrite = function(newfunc)     {         (var p io returnval)         {             if (returnval[p] === overwriteme)             {//update references                 returnval[p] = newfunc;                 break;             }         }         overwriteme = newfunc;//overwrite closure reference     },     returnval = {         overwrite: overwrite,         myfunc: overwriteme     }; }()); 

though must that, i'd think alternative ways acchieve whatever you're trying do. closure, imo, should treated whole. replacing parts of willy-nilly prove nightmare: don't know closure function @ given point in time, changed, previous state was, , why changed.
temporary sollution might this:

var foo = (function() {     var calc = function(x, callback)     {         callback = callback || defaultcall;         return callback.apply(this, [x]);     },     defaultcall(a)     {         return a*a+1;     },     return {calc: calc}; }()); foo(2);//returns 5 foo(2,function(x){ return --x;});//returns 1 foo(2);//returns 5 again 

imo, lot safer, allows choose different "internal" function used once, without changing core behaviour of code.


Comments