微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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中是否有任何改变,但我想它不会.

原文地址:https://www.jb51.cc/js/157036.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐