How to avoid using "this" in Javascript prototypes

javascript, prototypal-inheritance, this

Solution

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.

Problem

Here's my javascript object, I would like to know how to avoid using "this" so many times in prototype. I know there is lot of theory and links for prototypal inhericance and this has probably been answered already, but as I haven't been able to make all ends meet, I thought this may be worth another question. ``` function shape(smth) { this.a = smth this.b = 2 this.c = 3 } shape.prototype.doCalculus = function () { return this.a * this.b + this.c - (2 * (this.b + this.c) + this.a); } module.exports = shape ```

Original source