Aviv Cohn
Aviv Cohn

Reputation: 17243

When emulating a 'class', why set the methods in the .prototype property and not in the constructor itself?

I'm trying to understand 'classes' in JavaScript.

Usually emulating classes in JavaScript looks something like this:

function MyClass(someParameter) {
    this.someValue = someParameter;
    this.someOtherValue = "green";
}

MyClass.prototype.someMethod = function() {
    console.log("Hello!");
};

While the non-function members are set inside the constructor, the method is added outside of the constructor, to the .prototype property of the constructor.

I'd like to understand why. Why not create the methods inside the constructor, just like the rest of the members? Meaning:

function MyClass(someParameter) {
    this.someValue = someParameter;
    this.someOtherValue = "green";

    this.someMethod = function() {
        console.log("Hello!");
    }
}

Upvotes: 1

Views: 42

Answers (2)

Felix Kling
Felix Kling

Reputation: 816820

Why not create the methods inside the constructor, just like the rest of the members?

Because methods are usually not distinct between instances. In your example every instance has the same someMethod method, doing the exact same thing. So it only makes sense to create that method only once.

Scalar data on the other hand is often specific to the instance (i.e. distinct between instances) and thus should be initialized in the constructor.


FWIW, ECMAScript6 introduces the new class syntax which encourages such structure.

function MyClass(someParameter) {
    this.someValue = someParameter;
    this.someOtherValue = "green";
}

MyClass.prototype.someMethod = function() {
    console.log("Hello!");
};

is equivalent to

class MyClass {
    constructor(someParameter) {
        this.someValue = someParameter;
        this.someOtherValue = "green";
    }

    someMethod() {
       console.log("Hello!");
    }
}

Upvotes: 1

Amir Popovich
Amir Popovich

Reputation: 29846

Here are some main points:

  • Performance: Ctor methods are created each time an instance is created while prototype methods are created once and inherited.prototype is better here.
  • Ctor methods have access to privates inside your function while prototype ones don't.

Upvotes: 1

Related Questions