Search code examples
javascripttypestypeof

Typeof object is not function even though it implements [[Call]]


I am new to Javascript, so apologies if this has a trivial answer.

According to the ECMAScript language specification, if the return type of a val is Object (implements [[Call]]) then the result is the string "function". What I don't understand is why in the following code, the type of the newly created object is not "function":

function FunctionCreator(){}

FunctionCreator.prototype = Function.prototype;

let obj = new FunctionCreator();

console.log(typeof obj); // object
console.log(obj.call); // ƒ call() { [native code] }

The [[Call]] method is defined in Function.prototype, the same way I believe it is defined for a normal function, and yet typeof returns object.


Solution

  • obj isn't a function, it's an object created via the new operator. FunctionCreator is a function, but it doesn't create functions. Just making its prototype Function.prototype doesn't make what it creates functions, it just makes the object inherit properties that can't be usefully used, because it's not a function.

    The [[Call]] method is defined in Function.prototype...

    This may be what you're misunderstanding. Function.prototype has a call method, but that is not the [[Call]] internal method. It's just a method called call. [[Call]] is not accessible externally (and depending on the implementation of the JavaScript engine, it may not literally exist; it's a specification mechanism).

    To create a function, you use a function declaration, function expression, method definition, etc. (more here); or if you can't avoid them and you know the dangers associated with them, eval or new Function.