Question

I would like to have some sort of lazy initialied object properties in javascript and would thus want to somehow overload the property read and write access i.e.:

var someval = myobj.lazyprop; // invokes myobj.get("lazyprop");
myobj.lazyprop = someval;     // invokes myobj.set("lazyprop",someval);

where myobj is some object I provide to the script.

Rationale: I want to use Javascript (Rhino) as scripting engine in an application and the datastructures that need to be accessible by the scripts can be very large and complex. So I don't want to wrap them all in advance to javascript objects, esp. since the average script in this application will only need a very small subset of them. On the other hand I want the scripts to be as simple and readable as possible, so I don't want to require the use of get or set methods with string arguments explicitly in the scripts.

Was it helpful?

Solution

You can do it using Rhino 1.6R6 or higher with javascript getters and setters.

function Field(val){
   var value = val;

   this.__defineGetter__("value", function(){
       return value;
   });

   this.__defineSetter__("value", function(val){
       value = val;
   });

}

Now, if we wanted to, instead, define getters and setters within the context of our object prototype (and where having "private" data is less of a concern) we can then use an alternative object syntax for that.

function Field(val){
   this.value = val;

}

Field.prototype = {
   get value(){
       return this._value;
   },
   set value(val){
       this._value = val;
   }

};

OTHER TIPS

many js engines support getters and setters on javascript objects:

var obj = {
  get field() {alert('getting field');}
  set field(val) {alert('setting field to ' + val);}
}

var x = obj.field     // alert pops up
obj.field = 'hello'   // alert pops up

more details:

http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/

Rhino versions > 1.6R6 support getters and setters, you could write something like this:

var myobj = {
  // a getter and setter
  get lazyprop(){ return this.get('lazyprop'); },
  set lazyprop(val){ return this.set('lazyprop', val); },

  // the logic of your get and set methods:
  get: function(p) { return this['_'+p]; },
  set: function(p, val) { this['_'+p] = val; }
};

I think this is something you should do using the Rhino-specific API from the Java side; not from Javascript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top