I've got a really interesting javascript pattern that I've been
scratching my head over for a while. I basically understand what is
going on with what I'm about to talk about, but I would like a fuller
explanation than what I've been able to find on my own. Method
invocation at declaration:
        I was wandering around the MooTools source code to figrure out what I
could learn and I ran into an interesting method attached to the
global 'Function' that basically allows for all new functions to have
a method that allows them to take their arguments regular-style
"function( a , b ){}" or as an object "function( { a , b } ){}". The
code goes as follows (I've eliminated some of the other things that it
does, such as circumventing a problem in IE where if a property with
the DontEnum attribute exists in the prototype chain, or if the
instance property is marked DontEnum, it is not enumerated, such as
'hasOwnProperty'):

Function.prototype.overloadSetter = function(usePlural){
        var self = this;
        return function(a, b){
                if (a == null) return this;
                if (usePlural || typeof a != 'string'){
                        for (var k in a) self.call(this, k, a[k]);
                } else {
                        self.call(this, a, b);
                }
                return this;
        };
};

This isn't the interesting thing yet. What is interesting about this
function is how it is invoked. It absolutely has to be invoked at
declaration, it will not work if it isn't invoked at its invoker's
invocation. Here is a function that uses it that sets an string and
some other object as an extension:

Function.prototype.extend = function(key, value){
        this[key] = value;
}.overloadSetter();

So we could use this to basically do something like this:

someFunc.extend( 'someMethod' ,  function(){does something} ); OR
someFunc.extend( { 'someMethod' : function(){does something} } );

My question doesn't revolve so much around 'how does this work', but
as to 'why does this work', so if you're 100% sure of EXACTLY why this
is working than please tell me. Before you do consider that this
pattern can only be used on the global 'Function' object (seriously
try it), it cannot be used in some other parent object basically you
couldn't replace the word 'Function' in the above code with anything
else, this ONLY works with the global 'Function' object, but why? I
guess that's my question. I understand all of the above code and how
it's working, but I don't understand why it's working.

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to