Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: function.prototype.method

Tags:

javascript

I guess most of you have seen the following code snippet:

Function.prototype.method = function (name, func) {
  this.prototype[name] = func;
  return this;
};

I also know that it will affect all functions since they are all objects created by Function so that they can access method named "method", however I am confused why Function itself also can also access "method" like following:

Function.method('test', function () {return 1;});
like image 594
sunqiang.leo Avatar asked Jul 03 '13 11:07

sunqiang.leo


2 Answers

Edorka's answer is correct: Function is its own constructor (i.e. "parent").

Function.constructor;  // function Function() { [native code] }

Normally you can't do what you're doing. For example, this won't work:

f = function () {};
f.prototype.a = 5;
f.a;  // undefined

This kind of thing only works if you use a function as a constructor, like so:

f = function () {};
f.prototype.a = 5;
g = new f();
g.a;  // 5

But Function is weird, it is the constructor for all functions and is also a function itself, so it templates its properties off its own prototype. Hence you can call Function.method() in your code.

like image 114
Chris Avatar answered Sep 24 '22 20:09

Chris


Because Function is itself a function:

typeof Function === 'function'
Object.getPrototypeOf(Function) === Function.prototype

And you can see it being called as a function (a form of indirect eval):

Function('return 1+2')() === 3

All that as defined in the spec.

zerkms asked in a comment above:

Which came first - the Function object or the Function prototype?

We have to understand that what's exposed to us, the puny programmers, is different than what's represented internally. This can be exemplified by overriding the Array constructor (tip: don't try this while writing an answer, you'll get a lot of errors):

new Array(0, 1, 2); //gives you [0, 1, 2]
Array = function () { return [4] };
new Array(0, 1, 2); //gives you [4]
//however,
[0, 1, 2] //will always give you [0, 1, 2]

This is because of a section in the spec (a bit down, in the "semantics" section):

Let array be the result of creating a new object as if by the expression new Array() where Array is the standard built-in constructor with that name.

Using the array literal (or array initializer as the spec calls it) you ensure that you use the built-in Array constructor.

Why did I give this example? First of all, because it's a fun example. Second, to demonstrate how what we do and what's actually done are different. To answer zerkms, the Function object most likely came first, but that was not the first function. We don't have access to that built-in function.

like image 37
Zirak Avatar answered Sep 23 '22 20:09

Zirak