gpt4 book ai didi

javascript - 为什么如果 F - 简单函数 : F. 原型(prototype)!== F.__proto__ 但 Function.prototype === Function.__proto__?

转载 作者:太空宇宙 更新时间:2023-11-04 15:40:01 24 4
gpt4 key购买 nike

为什么如果F - 简单函数:

F.prototype !== F.__proto__

但是

Function.prototype === Function.__proto__ 

最佳答案

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并使用 prototype 属性将其设置为 F 的所有实例的原型(prototype):

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__

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

关于javascript - 为什么如果 F - 简单函数 : F. 原型(prototype)!== F.__proto__ 但 Function.prototype === Function.__proto__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43962856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com