I’m just reading about Prototypes in JavaScript and Douglas Crockford offers and excellent way to select a new objects prototype but can anyone explain (below) why obj01’s type equals ‘object’ when I pass it in function as it’s prototype?
if (typeof Object.beget !== 'function') {
Object.beget = function (o) {
console.log(typeof o);//function
var F = function () {};
F.prototype = o;
console.log(typeof F);//function
return new F();
};
}
var func01 = function(){};
var obj01 = Object.beget(func01);
console.log(typeof obj01);//object
console.log(typeof obj01.prototype);//object
I thought it would be
console.log(typeof obj01);//function
console.log(typeof obj01.prototype);//function
obj01is simply an object that inherits from a function object, you can’t create functions in this way.The
typeofoperator returns"function"only when its operand is by itself callable.There are only three valid ways to create function objects:
Function declaration:
Function expression:
Function constructor:
Edit: In response to your comment,
obj01, is just an object, its prototype chain contains a function object, thenFunction.prototypeand thenObject.prototypebut that doesn’t make an object callable.Your object is not callable, functions are just objects, but they have some special internal properties that allow them to behave like that.
An object is callable only if it implements the internal
[[Call]]property.There are other internal properties that function objects have, like the
[[Construct]], which is invoked when thenewoperator is used, the[[Scope]]property which stores the lexical environment where the function is executed, and more.If you try to invoke your object like if it were a function, you will have a
TypeError, because when you make a function call, the object needs to have the[[Call]]internal property.Function objects need to have the above internal properties, and the only way that they can be constructed is by the three methods I mentioned early, you can see how internally functions objects are created here.