Javascript Combining Variables Inside An Object
Okay this seems really simple but I just can't get it to work. I need to combine variables in an obect. Something like this: var i = { a: 1, b: ' sheep', c: this.a + th
Solution 1:
Use a function.
var i = {
a: 1,
b: " sheep",
c: function () {
returnthis.a + this.b;
}
}
i.a = 3;
console.log(i.c());
This looks like it but is there anyway to avoid the function call (). I've seen get and set used in objects. Is this something that is widely used?
Sure, you can use getters, but they won't work in IE <9 (while the above code will), and there's no way to shim it since it relies on a completely new language syntax.
var i = {
a: 1,
b: " sheep",
get c() {
returnthis.a + this.b;
}
}
i.a = 3;
console.log(i.c);
Solution 2:
It is possible in object literal only if you do:
var i = {
a: 1,
b: " sheep",
c: function() { returnthis.a + this.b; }
};
console.log( i.c() );
Solution 3:
var i = {
a: 1,
b: " sheep",
c: function () { returnthis.a + this.b }
}
i.a = 3;
console.log(i.c());
Post a Comment for "Javascript Combining Variables Inside An Object"