L
Lachlan Hunt
Hi,
In JavaScript 1.5, objects can use special getter and setter functions
[1] for properties. However, these only seem to be implemented in Gecko
and, AFAICT, don't seem to be part of ECMAScript.
Is there an alternative syntax I can use that is standardised in
ECMAScript and also (preferably) interoperably implemented in several
browsers? Or, do I have to use ordinary getFoo() and setFoo() functions.
Example using JS 1.5 Getters and Setters:
(only works in Gecko)
// Prototype
function something() {
var foobar = "bar"
// logic to validate val argument omitted
this.foo setter = function(val) { return foobar = val; }
this.foo getter = function() { return foobar; }
}
// Create instance
var thing = new something();
// Use properties
alert("Before: foo = " + thing.foo);
thing.foo = "baz";
alert("After: foo = " + thing.foo);
Example using getFoo() and setFoo() functions:
(works in everything tested, including IE, Opera and Firefox)
// Prototype
function something() {
var foo = "bar"
// logic to validate val argument omitted
this.setFoo = function setFoo(val) { foo = val; };
this.getFoo = function() { return foo; };
}
// Create instance
var thing = new something();
// Use properties
alert("Before: foo = " + thing.getFoo());
thing.setFoo("baz")
alert("After: foo = " + thing.getFoo());
[1]
http://www.jalix.org/ressources/internet/javascript/_JS15guide/JS15core/obj.html#1018325
In JavaScript 1.5, objects can use special getter and setter functions
[1] for properties. However, these only seem to be implemented in Gecko
and, AFAICT, don't seem to be part of ECMAScript.
Is there an alternative syntax I can use that is standardised in
ECMAScript and also (preferably) interoperably implemented in several
browsers? Or, do I have to use ordinary getFoo() and setFoo() functions.
Example using JS 1.5 Getters and Setters:
(only works in Gecko)
// Prototype
function something() {
var foobar = "bar"
// logic to validate val argument omitted
this.foo setter = function(val) { return foobar = val; }
this.foo getter = function() { return foobar; }
}
// Create instance
var thing = new something();
// Use properties
alert("Before: foo = " + thing.foo);
thing.foo = "baz";
alert("After: foo = " + thing.foo);
Example using getFoo() and setFoo() functions:
(works in everything tested, including IE, Opera and Firefox)
// Prototype
function something() {
var foo = "bar"
// logic to validate val argument omitted
this.setFoo = function setFoo(val) { foo = val; };
this.getFoo = function() { return foo; };
}
// Create instance
var thing = new something();
// Use properties
alert("Before: foo = " + thing.getFoo());
thing.setFoo("baz")
alert("After: foo = " + thing.getFoo());
[1]
http://www.jalix.org/ressources/internet/javascript/_JS15guide/JS15core/obj.html#1018325