gpt4 book ai didi

javascript - Crockford 的伪经典继承部分中的函数构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:43:07 24 4
gpt4 key购买 nike

这是什么意思:

"When a function object is created, the Function constructor that produces the function object runs some code like this:

this.prototype = {constructor: this};

The new function object is given a prototype property whose value is an object containing a constructor property whose value is the new function object"

最好能举例说明。

最佳答案

例如,当你定义这个构造函数时:

function MyConstructor() {
// ...
}

它自动接收一个 prototype 属性。它的值是一个具有 constructor 属性的对象,该属性指向构造函数:

MyConstructor.prototype; // some object
MyConstructor.prototype.constructor; // MyConstructor

这在 Creating Function Objects 中指定:

  1. Create a new native ECMAScript object and let F be that object.

  1. Let proto be the result of creating a new object as would be constructed by the expression new Object() where Object is the standard built-in constructor with that name.
  2. Call the [[DefineOwnProperty]] internal method of proto with arguments "constructor", Property Descriptor {[[Value]]: F, { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}, and false.
  3. Call the [[DefineOwnProperty]] internal method of F with arguments "prototype", Property Descriptor {[[Value]]: proto, { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false}, and false.

然后,构造函数的实例将从它的 prototype 对象继承:

var myInstance = new MyConstructor();
Object.getPrototypeOf(myInstance); // MyConstructor.prototype

如果您想知道用于创建实例的构造函数,您可以使用 constructor 属性,它有望被继承:

myInstance.constructor; // MyConstructor

关于javascript - Crockford 的伪经典继承部分中的函数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35855903/

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