Viraj
Viraj

Reputation: 797

Function constructor in Crockford's pseudoclassical inheritance section

What does he mean by this:

"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"

Explanation with an example would be great.

Upvotes: 3

Views: 130

Answers (1)

Oriol
Oriol

Reputation: 288100

For example, when you define this constructor:

function MyConstructor() {
   // ...
}

It automatically receives a prototype property. Its value is an object with a constructor property, which points back to the constructor:

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

This is specified in 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.

Then, instances of the constructor will inherit from its prototype object:

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

In case you want to know the constructor used to create the instance, you can use the constructor property, which hopefully will be inherited:

myInstance.constructor; // MyConstructor

Upvotes: 6

Related Questions