How to avoid using "this" in Javascript prototypes

It's possible to avoid using this in the constructor, by using Object.create to create the prototype chain, then declaring your properties directly on the resulting object.

function Shape(smth) {
  var shape = Object.create(Shape.prototype);

  shape.a = smth;
  shape.b = 2;
  shape.c = 3;

  return shape;
}

This removes the need for this in your Shape function, meaning that we no longer need to call it with new either.

new Shape(1); // { a: 1, b: 2, c: 3, __proto__: Shape.prototype }
Shape(1);     // { a: 1, b: 2, c: 3, __proto__: Shape.prototype }

However, you'll still need to use this inside your prototype methods to refer to the correct instance.


If you want public members of an object, they MUST be referenced from the this pointer. That's how OO works in Javascript. No alternative.

If you have lots of references to the same variable within a function, you can temporarily put it in a local variable just to save some reference logic (same as with any multiple step reference), but you will still have to initially retrieve using this.varName.


There is a scheme that uses "private" member variables in a constructor closure and does not use the prototype that can be used in some situations and this allows you to refer to the variables directly without this use of this:

function shape(smth) {
    var a = smth,
        b = 2,
        c = 3;

    this.doCalculus = function() {
        return a * b + c - (2 * (b + c) + a);
    }
}

module.exports = shape

For object types where you create lots of instances, this may consume a bit more memory because methods are not stored on a shared prototype, but are created separately for each instance. There are those who argue the difference in memory consumption is immaterial in most uses.