x is not a function … what would you expect Object.create to do with a constructor

前端 未结 2 1150
后悔当初
后悔当初 2020-12-19 07:13

For this question, I\'m not expecting a solution to solve something but would like to understand things better ..

Some quote from the specifications:

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 08:11

    Unfortunately that won't work. What you have is an object that has F in its prototype chain; the fact that F is a function doesn't make x a function.

    Only objects created via a function declaration or a function expression will have "Function" as their [[Class]], and a [[Call]] method, which makes it callable. Those are created according to the steps detailed on section 13.2 of the ECMAScript 5 specification.

    The algorithm for Object.create does something different, as you can see on your quote. In your case, x will be a regular object with [[Class]] "Object" and no [[Call]] method. If you try Object.prototype.toString.call(x), you'll get "[object Object]", where "Object" is the [[Class]] of x. x instanceof Function only returns true because the Function constructor is part of the prototype chain of x (via F).

    I'm not sure if any of that is going to be changed in ES6, but I suppose it won't.

提交回复
热议问题