Reputation: 17243
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
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
Reputation: 29846
Here are some main points:
Upvotes: 1