javascript - Resolve two anonymous functions to the same definition point? -



javascript - Resolve two anonymous functions to the same definition point? -

i have code in next form in user may specify callback called @ later time:

class="lang-js prettyprint-override">var _deferred = []; var deferred = function(callback) { _deferred.push(callback); } var dodeferred = function() { for(var = 0, max = _deferred.length; < max; i++) { _deferred[i].call(); } } for(var = 0; < 5; i++) { deferred(function() { console.log("some deferred stuff"); }); } dodeferred();

i recognize callback specified deferred() anonymous function resolving same origin, , allow added once. aka in bottom loop throw exception when = 1.

like:

class="lang-js prettyprint-override">var deferred = function(callback) { if(_deferred.indexof(callback) !== -1) { throw "already added!"; } _deferred.push(callback); }

i can think of many ways of doing adding "key", i'm wondering if can utilize along lines of function.caller create "source hash"?

is there solution out there i'm not seeing? i'd prefer take burden onto myself rather force out caller of deferred , have them provide sort of unique id.

edit:

to clarify confusion.

yes each phone call deferred unique function object, has own closure, etc. hence indexof fail. not point of confusion.

the question these anonymous functions declared in same place, same code, how can determine that? i'm looking determine declarative equality, not instance equality. thinking somehow create hash based on caller of deferred...

conclusion:

thanks guys, seems there no elegant solution here. tostring method not definitive (different functions same body test as strings) - , ugly. i'm going set burden on caller.

the thing is, in loop @ bottom, are different functions, in fairness should both included (and honestly, there no guarantee values both functions won't different depending on variables nowadays @ moment). i'm not sure 'unique functions only' people expect, might cause deal of "debugging"

this isn't required of ecmascript, function.tostring() homecoming internal structure. want:

var ids = [] // separate id takes more space, lookup should // faster. var deferred = function(callback) { var cbs = callback.tostring() // or string(callback) if(ids.indexof( cbs ) !== -1) { throw "already added!"; } ids.push( cbs ) _deferred.push(callback); }

if you're willing utilize for... in loop:

var _deferred = {} var deferred = function(callback) { var cbs = callback.tostring() // or string(callback) if( _deferred[ cbs] ) { throw "already added!"; } _deferred[ cbs] = callback; } // caution, executes in arbitrary order. var dodeferred = function() { for(var in _deferred) { _deferred[i].call(); } }

javascript

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -