Reputation:
I have the below code:
function Class () {
this.method = function () {
alert('method');
};
}
new Class().method();
And it works fine, but as I understand, for each new object will be created the function. Is there right way to do this?
Upvotes: 2
Views: 372
Reputation: 6209
My approach is almost identical to Speransky's, but I re-declare the prototype object instead of adding methods directly to it.
// Declare the Constructor function.
function MyClass (name, age) {
// Assign any member properties here.
this._name = name;
this.age = age;
}
// Redefine the prototype object to add methods.
MyClass.prototype = {
// Re-point the Constructor function as it will be overwritten.
constructor: MyClass,
// Custom method which all instances of `MyClass` will inherit.
sayHello: function () {
return "My name is " + this._name + ", how do you do?";
}
};
Usage:
var foo = new MyClass("Dave", 22);
foo.sayHello(); // "My name is Dave, how do you do?"
foo.age; // 22
If you wanted to point the MyClass
prototype at another object (to setup a simple inheritance model) then you could make use of a mixin, similar to Underscore's extend
method:
function BaseClass(name) {
this._name = name;
}
BaseClass.prototype = {
constructor: BaseClass,
sayHello: function () {
return "My name is " + this._name + ", how do you do?";
}
}
class MyClass (name, age) {
// Call the BaseClass constructor function in the context of `this`
BaseClass.call(this, name);
this.age = age;
}
// Mixin the BaseClass's protptype into the MyClass prototype and delcare
// the new methods.
_.extend(MyClass.Prototype, BaseClass.prototype, {
constructor: MyClass,
getAge: function () {
return this.age;
}
});
Upvotes: 0
Reputation: 30453
Place initialization of instance varibales into the Class function, and shared methods and variables in prototype property:
function Class (var1, var2) {
this.var1 = var1;
this.var2 = var2;
}
Class.prototype.method = function () {
alert(this.var1 + ' ' + this.var2);
};
new Class('var1', 'var2').method();
Upvotes: 5