javascript – x不是函数…你期望Object.create对构造函数做什么

前端之家收集整理的这篇文章主要介绍了javascript – x不是函数…你期望Object.create对构造函数做什么前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对于这个问题,我不期望解决问题的解决方案,但希望更好地理解事情.

一些引用规格:

>版本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:

    @H_502_12@If Type(O) is not Object or Null throw a TypeError exception. @H_502_12@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 @H_502_12@Set the [[Prototype]] internal property of obj to O. @H_502_12@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. @H_502_12@Return obj.

>第6版 – 草稿(Link)

§19.1.3.2 Object.create ( O [,the following steps are taken:

    @H_502_12@If Type(O) is not Object or Null throw a TypeError exception.
      @H_502_12@Let obj be the result of the abstract operation ObjectCreate with argument O. @H_502_12@If the argument Properties is present and not undefined,then
      a. Return the result of the abstract operation ObjectDefineProperties(obj,Properties). @H_502_12@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对构造函数做什么?

解决方法

不幸的是,这不会奏效.你拥有的是一个在其原型链中具有F的对象; F是函数的事实不会使x成为函数.

只有通过函数声明或函数表达式创建的对象才会将[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中是否有任何改变,但我想它不会.

猜你在找的JavaScript相关文章