Javascript prototype question

I'm just reading about prototyping in JavaScript and Douglas Crockford has a great way to pick a prototype for new objects as well, but can anyone explain (below) why obj01 is "object" when I pass it as a 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

      

+2


a source to share


2 answers


obj01

is just an object that inherits from a function object, so you cannot create functions.

An operator only typeof

returns "function"

if its operand itself is callable.

There are only three valid ways to create function objects:

Function declaration:

function name (/*arg, argn...*/) {
}

      

Functional expression:

var fn = function /*nameopt*/ (/*arg, argn...*/) {
};

      

Function constructor:



var fn = new Function("arg", "argn", "FunctionBody");

      

Edit: In response to your comment obj01

- it's just an object, its prototype chain contains a function object, then Function.prototype

and then Object.prototype

, but that doesn't make the object callable.

Object is not callable, functions are just objects, but they have some special internal properties that allow them to behave like this.

An object can only be called if it implements an internal property[[Call]]

.

There are other intrinsic properties that function objects have, such as [[Construct]]

which is called when new

, the property [[Scope]]

retains the lexical environment in which the function is executed, and much more.

If you are trying to call your object as if it were a function, you will TypeError

because when you call a function call , the object must have an internal property [[Call]]

.

Function objects must have the above internal properties and the only way they can be constructed is with the three methods I mentioned earlier, you can see how the internal function objects are created here .

+4


a source


It is really very simple.

The variable F

points to a function, so it typeof F

returns 'function'.

But the return value from F()

is an object, execution context (activation object), or an instance of a class, if you like. For more information on this, read this excellent blog series .



It typeof F()

returns 'object' for this.

As Martin showed in his comment; change return new F();

to return F;

. This should return a new function with the modified scope chain used to create the new "subclass".

+1


a source







All Articles