javascript interactive

JavaScript Interactive — a console crash course


5.2 Classes vs. Prototypes

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.

JavaScript uses dynamic and prototype-based objects, not classes. It is a more general model:

  1. Ad-hoc or "classless" objects are easily created and very usable (i.e. instances of Object).
  2. Properties and methods can be added and modified at any time.
  3. Any object can be reused (cloned or copied), not just "class" objects.
  4. Prototype modifications affects all objects, even if created previously.
>>>
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.
>>>
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 both the property name and value (the function object).
>>>
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 obj = {
    test: function () {
        return 123;
    }
}

  
When only a single instance is created, it may be more convenient to create an ad-hoc object (an object literal) instead. There are no particular drawbacks with this approach, except readability when objects become large.
>>>

Index 1 2 3 4 5 6 7 8