一些引用规格:
>版本5.1(Link)
§15.2.3.5 Object.create ( O [,Properties] )
The create function creates a new object with a specified prototype. When the create function is called,the following steps are taken:
- If Type(O) is not Object or Null throw a TypeError exception.
- Let obj be the result of creating a new object as if by the expression new Object() where Object is the standard built-in constructor with that name
- Set the [[Prototype]] internal property of obj to O.
- If the argument Properties is present and not undefined,add own properties to obj as if by calling the standard built-in function Object.defineProperties with arguments obj and Properties.
- Return obj.
>第6版 – 草稿(Link)
§19.1.3.2 Object.create ( O [,the following steps are taken:
- If Type(O) is not Object or Null throw a TypeError exception.
- Let obj be the result of the abstract operation ObjectCreate with argument O.
- If the argument Properties is present and not undefined,then
a. Return the result of the abstract operation ObjectDefineProperties(obj,Properties).- Return obj.
如果我理解正确,两个规范都允许执行以下代码:
function F() { } var x=Object.create(F); // a minimal test alert(x.prototype.constructor===F); // true alert(x instanceof Function) // true alert(typeof x) // 'object'
似乎它创建了一个类型的对象派生自(抱歉可怜的术语..)我在FireFox中测试的函数,因此x是不可调用的:
x(); // x is not a function
我在考虑为什么它不会禁止将构造函数用作O或只是创建一个有效的构造函数.
所以我想知道你期望Object.create对构造函数做什么?
解决方法
只有通过函数声明或函数表达式创建的对象才会将[Function]作为[[Class]],并使用[[Call]]方法使其可调用.这些是根据section 13.2 of the ECMAScript 5 specification详细说明的步骤创建的.
Object.create的算法做了不同的事情,正如您在引用中看到的那样.在您的情况下,x将是[[Class]]“Object”且没有[[Call]]方法的常规对象.如果你尝试Object.prototype.toString.call(x),你会得到“[object Object]”,其中“Object”是x的[[Class]]. x instanceof函数只返回true,因为Function构造函数是x(通过F)原型链的一部分.
我不确定ES6中是否有任何改变,但我想它不会.