Idan Yadgar
Idan Yadgar

Reputation: 1034

"Function" is function, how is that possible?

In js we have a function named "Function". An instance of it returns a function:

var myfunc = new Function('arg1','arg2','return arg1+arg2');

In that example the variable myfunc contains a function that returns the sum of two given params.

My question is - how is that possible that Function is a function? It can't be an instance of itself. And Object is a function too, an instance of Function. But Function is an instance of Object because function are objects.

And I can't understand how is it possible, it's an infinity loop...

Thanks.

Upvotes: 0

Views: 86

Answers (2)

RobG
RobG

Reputation: 147413

The trivial answer is "because ECMA-262 says so".

Objects like Function, Object, Array, Date etc. are built–in objects so they aren't constructed in the usualy way, they just are. The relationship between them, their prototype and their [[Prototype]] is established by the environment in accordance with ECMA-262. So Function inherits from its own prototype (i.e. Function.prototype === Function[[Prototype]]), which inherits from Object.prototype.

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318518

Object, Function, etc. are indeed functions - constructor functions to be exact.

Remember, you create an object like this:

function MyObject() {
    this.foo = 'bar';
}

var my = new MyObject();
alert(my.foo);

By the way, using new Function(...) is usually a bad idea. Your example would be much cleaner like this:

function myfunc(arg1, arg2) { return arg1 + arg2 }

or

var myfunc = function(arg1, arg2) { return arg1 + arg2 };

So there are few reasons to use new Function() in production (template engines are a good usecase for it though).

Upvotes: 2

Related Questions