Console Learner — An interactive JavaScript course.


4.6 Prototype Chains

>>>
function A() {
    this.test = function () { return 123; };
}

  
This example illustrates a common mistake. Since test() is declared inside the constructor function, a new function object will be created for each new A instance.
>>>
print(new A(), true);

  
The test property is also added to each instance, instead of the prototype. In this console, a prototype chain can be inspected with print(..., true).
>>>
function B() {}


  
>>>
B.prototype.test = function () {
    return 123;
};

  
Declaring test() outside the constructor and using the constructor prototype is better.
>>>
print(new B(), true);

  
The prototype chain for B shows that instances share the test property (method).
>>>
function C_test() { return 123; }


  
>>>
function C() {
    this.test = C_test;
}

  
Another option would be to declare the test() function outside the constructor, but still add it to each instance. This is practical in some circumstances, but doesn't take advantage of the prototype object.
>>>
var D = {
    test() {
        return 123;
    }
};

  
For singleton (one-off) instances, it is more convenient to create an object literal instead. Since ES6 (2015), a shorthand method syntax is even available that omits the function keyword.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.