Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neat alternatives to __defineGetter__?

Getters and setters are a beauty in VB.Net:

Get
    Return width
End Get
Set(ByVal value As Integer)
    width = value
End Set

In Javascript, this is probably what we would do:

function Test() {
    var width = 100;
    this.__defineGetter__("Width", function() {
        return width;
    });
    this.__defineSetter__("Width", function(value){
        width = value;
    });
}

It looks like a plate of spaghetti ransacked by a kuri. What are some neater alternatives we have?

Note: The new code should access the value using new Test().Width and not new Test().Width().

like image 793
Pacerier Avatar asked Apr 20 '11 13:04

Pacerier


1 Answers

With ES5 you'll be able to do:

function Test() {
  var a = 1;

  return {
    get A() { return a; },
    set A(v) { a = v; }
  };
}

The getter/setter functions can of course do anything you want them to.

like image 169
Pointy Avatar answered Oct 01 '22 11:10

Pointy