【问题标题】:Why if F - simple function: F.prototype!== F.__proto__ but Function.prototype === Function.__proto__?为什么如果 F - 简单函数:F.prototype!== F.__proto__ 但 Function.prototype === Function.__proto__?
【发布时间】:2017-05-14 10:29:23
【问题描述】:

为什么F - 简单函数:

F.prototype !== F.__proto__

但是

Function.prototype === Function.__proto__ 

?

【问题讨论】:

  • Function.prototype === Function.__proto__
  • 因为Function是一片特殊的雪花?
  • 你为什么会期待它不是这样?您还期望它指的是什么?
  • __proto__ 已弃用,您不应再使用它。请改用Object.getPrototypeOf(…)
  • Read the spec,它是这样定义的:“Function构造函数的[[Prototype]]内部槽的值是内部对象%FunctionPrototype%”。

标签: javascript oop prototype proto function.prototype


【解决方案1】:

F.prototype !== F.__proto__

假设您正在为所有函数设计一个 API。所以你定义每个函数都应该有方法call。你用这样的方法创建一个对象:

var fproto = {call: ()=>{}};

然后,要让所有函数共享此功能,您必须将其添加到 Function 构造函数 so that all instances of a Function inherit it.prototype 属性中。因此,您执行以下操作:

Function.prototype = fproto.

现在,当您创建函数F 时,它的.__proto__ 将设置为fproto

const F = new Function();
F.call(); // works because of lookup in prototype chain through `__proto__` property
F.__proto__ === Function.prototype; // true

现在您决定使用F 构造函数创建的所有实例都应该有一个方法custom,因此您使用该属性创建一个对象iproto,并将其设置为使用@ 的所有F 实例的原型987654335@财产:

const iproto = {custom: ()=>{}};
F.prototype = iproto;

const myobj = new F();
myobj.custom(); // works

所以现在应该清楚F.__proto__F.prototype 不是同一个对象。当你声明一个函数时,这基本上就是在幕后发生的事情:

const F = function() {};

// F.__proto__ is set to Function.prototype to inherit `call` and other methods
F.__proto__ === Function.prototype

// F.prototype is set to a new object `{constructor: F}` and so:
F.prototype !== Function.prototype

Function.prototype === Function.__proto__

这是一个例外情况,因为Function 构造函数应该具有可用于函数实例的所有方法,因此Function.__proto__,但所有这些方法都与函数实例共享这些方法,因此Function.prototype

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 2016-02-09
    • 2013-08-23
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多