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:

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

>第6版 – 草稿(Link)

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

  1. If Type(O) is not Object or Null throw a TypeError exception.
    1. Let obj be the result of the abstract operation ObjectCreate with argument O.
    2. If the argument Properties is present and not undefined,then
      a. Return the result of the abstract operation ObjectDefineProperties(obj,Properties).
    3. 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中是否有任何改变,但我想它不会.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...