tags:

views:

45

answers:

3

Hi all

I wanted to ask if there is a formal way of describing the following code, whereby we can access the same object repeatedly without re-typing the object's identifier:

myObj.render(1).render(2).print();

I didn't know how to describe it when trying to form a question; I wanted to know whether or not something like this is possible in javascript, I know that I can do it in VB:

myObj.render(1)
    if(foo == 'bar')
        .render(2)
    .print();

Thanks!

+1  A: 

Here's what I would go for:

var x = myObj.render(1);
if(foo == 'bar')
   x = x.render(2);
x.print();

You may also be interested in the with keyword, as in:

var a, x, y;
var r = 10;
with (Math) {
   a = PI * r * r;
   x = r * cos(PI);
   y = r * sin(PI / 2);
}

More details about it can be found here

Itay
Thanks, just fixed it.
Itay
+3  A: 
var obj = myObj.render(1);
if (foo == 'bar')
  obj = obj.render(2);
obj.print();
musicfreak
+2  A: 

The name you are looking for is fluent interface, your first example can easily be implemented like this:

var obj = {
  render: function (arg) {
    // do something here...
    return this; // the key of chainability
  },
  print: function () {
    alert('print something...');
  }
};

obj.render(1).render(2).print();

Basically the render method needs to return the object instance where it belongs, in order to allow chainability.

The conditional you want to do is not possible, you'll have make something like @musicfreak suggest.

CMS
I didn't know that, I always wondered how jQuery did it. Thanks!
Ben Shelock