PDA

View Full Version : Objects: Get/Set



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

Twey
07-05-2007, 08:19 AM
Yup, you're quite right, there's no real point to them. They're just syntactic sugar: they can be used to make things look nicer.

mwinter
07-05-2007, 04:28 PM
Yup, you're quite right, there's no real point to them. They're just syntactic sugar: they can be used to make things look nicer.

As I recall, it is a Gecko extension to ECMAScript, so it's pointless for the Web anyway.

Twey
07-05-2007, 04:40 PM
Yes, although it's included in Mozilla's ECMAScript 4 proposal. I think this proposal may have been rejected, however.

mwinter
07-05-2007, 04:51 PM
Yes, although it's included in Mozilla's ECMAScript 4 proposal. I think this proposal may have been rejected, however.

It would still be pointless for the Web until about five years after the proposal is accepted and first implemented in all "major" browsers. :)