When defining a JS object with a constructor function, is there any way to avoid having to use “this” with every single object property? It seems very ugly. E.g.
function Thingy(abc) {
this.var1 = abc;
this.var2 = this.var1 + " hello ";
// etc
}
var myObj = new Thingy();
It seems that I should be able to use “var var2” and then leave out the “this” and just refer to “var2”, but am I missing something?
Well, I’m afraid that you’re running into how the language is designed.
But there is a sense in which you can use the plain
varstatements from the constructor. Any functions created in there have access to the closure that includes these properties:Note this is how you can encapsulate entirely private variables in an object, so it’s often a useful technique.