Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Function.prototype and prototype-method assignment

Distinguish a function’s own prototype chain from the prototype of its instances, and share one method across those instances.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

Function.prototype
Object.getPrototypeOf(Constructor)
Constructor.prototype.method = function (arg) { /* method body */ };
const instance = new Constructor();
instance.method(arg);
Object.getPrototypeOf(instance)

Function.prototype is the built-in object from which an ordinary function such as Counter inherits call, apply, and bind. Use Object.getPrototypeOf(Counter) to inspect the prototype of the function itself. By contrast, Counter.prototype is an own property of the constructor: it refers to the object that new Counter(...) uses as the new instance’s prototype.

Counter.prototype.double = function () { return this.value * 2; }; stores the function on the prototype instead of copying it to each instance. For early.double(), JavaScript looks for an own double property on early first, then follows the prototype chain. Even though it finds the function on the prototype, this is early. An arrow function is not a substitute here: it takes this from its enclosing scope.

Adding a method to the existing prototype object also makes it available to older instances, unless an own property shadows it. By contrast, Counter.prototype = {} replaces the object used by subsequent new Counter(...) calls. Existing instances still point to the previous prototype.

Add instance methods to your own constructor’s prototype, not to Function.prototype. Changing that built-in prototype can also affect unrelated functions that inherit from it.

Examples

{
  function Counter(value) {
    this.value = value;
  }

  const early = new Counter(3);

  Counter.prototype.double = function () {
    return this.value * 2;
  };

  const late = new Counter(5);
  console.log(Object.getPrototypeOf(Counter) === Function.prototype);
  console.log(Object.getPrototypeOf(early) === Counter.prototype);
  console.log(early.double === late.double);
  console.log(late.double());

  Counter.prototype = {};
  console.log(early.double());
  console.log(typeof (new Counter(7)).double);
}

Result

true
true
true
10
6
undefined

`early` is created before the method is added but still inherits it. After the prototype is replaced, `early.double()` still returns `6`, while `typeof` returns `"undefined"` for the new instance’s `double` property.

Related lessons

  • JavaScript · Lesson 38 · Intermediate · Version: 3

Sources