Trinithis
07-05-2007, 03:50 AM
Could someone explain to me the purpose of "set" and "get"?
o = {
a:7,
get b() { return this.a+1; },
set c(x) { this.a = x/2; }
};
alert(o.a); // 7
alert(o.b); // 8
o.c = 8;
alert(o.a); // 4
alert(o.b); // 5
To me they seem like methods that are not methods, kind of like a mix between variables and methods.
But the way I see people normally code (or with slight variations, such as prototypes and such), the object would be coded like:
o = {
a:7,
b: function() { return this.a+1; },
c: function(x) { this.a = x/2; }
};
alert(o.a); // 7
alert(o.b()); // 8
o.c(8);
alert(o.a); // 4
alert(o.b()); // 5
o = {
a:7,
get b() { return this.a+1; },
set c(x) { this.a = x/2; }
};
alert(o.a); // 7
alert(o.b); // 8
o.c = 8;
alert(o.a); // 4
alert(o.b); // 5
To me they seem like methods that are not methods, kind of like a mix between variables and methods.
But the way I see people normally code (or with slight variations, such as prototypes and such), the object would be coded like:
o = {
a:7,
b: function() { return this.a+1; },
c: function(x) { this.a = x/2; }
};
alert(o.a); // 7
alert(o.b()); // 8
o.c(8);
alert(o.a); // 4
alert(o.b()); // 5