Why Typeof(function.prototype) Is Function
Solution 1:
From the specification:
The Function prototype object is the intrinsic object %FunctionPrototype%. The Function prototype object is itself a built-in function object. When invoked, it accepts any arguments and returns undefined. It does not have a [[Construct]] internal method so it is not a constructor.
NOTE
The Function prototype object is specified to be a function object to ensure compatibility with ECMAScript code that was created prior to the ECMAScript 2015 specification.
(my emphasis)
If we go to the ES5 spec, it says:
The Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined.
...without offering any explanation for why that would be the case. That language is essentially unchanged in ES1, ES2, ES3, and ES5. I think the original idea was basically that that was what gave it its function-ness, although typeof
(even in ES1) didn't look at the internal [[Class]]
, it looked at whether the thing implemented [[Call]]
(as it still does). When something goes back all the way to ES1, one frequently has to just invoke the "because Eich did the first JavaScript in 10 days and yeah, weird stuff happens when you do that" argument. :-)
Side note: By "object literal" I take it you mean "plain object." (An "object literal" — what the specifiation calls an object initializer — is just a way to write an object in source code. There are other ways to create plain objects.)
Solution 2:
An object literal is some JavaScript syntax for creating objects. It isn't a data type.
Functions are just a specific type of object in JavaScript. Anywhere you can have an object, you can have a function.
Solution 3:
Well, I don't think you mean object literal, as alluded to by other answers and comments.
alert(Function.prototypeinstanceofObject) // truealert(Function.prototypeinstanceofFunction) // truealert(typeofFunction.prototype) // function
It is an object. It's also a function. Also, all functions are objects. They're all following the rules just fine.
alert((function(){}) instanceofObject) // truealert((function(){}) instanceofFunction) // truealert(typeof (function(){})) // function
One big happy we-all-derive-from-Object family. Why should the prototype of Function not be a function?
Now if you wanna get weird... let's get weird.
var notAFn = Object.create(Function.prototype);
alert(notAFn instanceofFunction); // truealert(typeof notAFn); // object
And no, you can't call notAFn()
. Not until they add a call Symbol
for that. :)
Oh hey, feel free to tell me why this isn't a good answer. I'll try to improve it.
Post a Comment for "Why Typeof(function.prototype) Is Function"