2

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?

2 Answers 2

5

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();
​
Sign up to request clarification or add additional context in comments.

1 Comment

Totally correct, but be careful with assigning objects on the prototype, since they'll be shared amongst all instances. eg: Class.prototype.foo = []
0

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;
    }
});

1 Comment

You don't loose __proto__ as it's auto-magically injected via browsers. As for it breaking inheritance; I've updated my example to show how you could take advantage of a Mixin. Personally, I try to avoid inheritance based architectures in JavaScript and favour composition instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.