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

Function constructor in Crockford's pseudoclassical inheritance section

他这是什么意思:

"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