So just now I was trying to understand why the fuck following codes work:
Code Sample #1
1 2 3 4 5 6 7 8 9 10 11
The codes above implements a
superior function which mimics the
super in OO world on the object prototype thus enables it on ALL objects, thus making following codes possible:
Code Sample #2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
I can easily understand the Code Sample #2. The
superior() call seems really natural, and that’s just the way APIs / libraries are supposed to work, right?
So I head back to Code Sample #1 to try to understand how the magic happened behind the scenes.
1 2 3 4
This part is easy. It defines a
method function on the function prototype so all functions are benefitted from it, any function calls the
method() gets its prototype assigned a function as a property. So far so good.
Well, the answer, unlike the stupid poor me, you might already knew, is that the
Object is a function.
1 2 3 4 5 6
I felt my brain had just exploded. Wow. So I did some more experiments:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
So basically, hacking a
method() function onto
Function.prototype enables it for all functions including
Object, and hacking a
superior() function with invocation of
Object hacks it onto
Object.prototype thus enables it for all objects.
So, the Code Sample #1 is exactly the same as:
1 2 3 4 5 6
this binding rules, this line in Sample Code #2
get_name() function in
that which carefully protects
that in its closure and is ready to be called with
This reminds me the moment of ecstasy when I first understood Ruby object / class / singleton-class hierarchies. Aha moments like this is one of the reasons why it is so fascinating to be working in this field.
Yes, my brain hurts now and I need to rest. And yes I <3 programming.