Reputation: 1421
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?
Upvotes: 1
Views: 373
Reputation: 50807
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 var
statements from the constructor. Any functions created in there have access to the closure that includes these properties:
function Thingy(abc) {
var var1 = abc;
this.func1 = function(str) {return var1 + ", hello";};
}
var thing1 = new Thingy("Dan");
thing1.func1(); // => "Dan, hello"
Note this is how you can encapsulate entirely private variables in an object, so it's often a useful technique.
Upvotes: 2
Reputation: 5
try
function Thingy(abc) {
with(this)
{
var1 = abc;
var2 = this.var1 + " hello ";
// etc
}
}
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with
Upvotes: -2
Reputation: 32906
You can use any object you like and simply return
it at the end e.g.:
function Thingy(abc) {
var thingy = {};
thingy.var1 = abc;
thingy.var2 = thingy.var1 + " hello ";
return thingy;
}
Or
function Thingy(abc) {
var thingy = {
var1: abc,
var2: abc + " hello "
};
return thingy;
}
Or
function Thingy(abc) {
return {
var1: abc,
var2: abc + " hello "
};
}
Or
function Thingy(abc) {
var var1 = abc,
var2 = var1;
var2 += " hello ";
return {
var1: var1,
var2: var2
};
}
Upvotes: 2
Reputation: 53351
Nope, there's no way to avoid it. You need to use this
to assign variables to an object.
Upvotes: 1