mathematical.coffee
mathematical.coffee

Reputation: 56915

Javascript attach an object syntactic sugar?

I have an object in my class like so:

this.options = {
     a: 1,
     b: 2,
     ...
};

I just wondered if there was a way to "attach" the options object to the current scope in Javascript, such that I can refer to a and b directly (instead of this.options.a and this.options.b). Something like:

attach(this.options);
var myVariable = a + 3; // 4
detach(this.options);

or

with( this.options, {
   // code here
 var myVariable = a + 3; // 4
});

In the above, the attach and with have the effect of taking all of the children of this.options and attaching them to the current scope so they are accessible via a instead of this.options.a. (The with version simply detaches this.options once you're done, enclosing the potentially-damaging attaching to within that scope).

As long as it works in the Spidermonkey/Mozilla engine, I don't mind if it's not portable.

I only mention this because of curiosity & laziness: all the nested names are getting annoying to type out, and I know that in the R language this is possible (in fact, the syntax in the snippets above is almost exactly what you'd write in R to achieve this).

Upvotes: 1

Views: 92

Answers (2)

nnnnnn
nnnnnn

Reputation: 150030

JavaScript has a with statement that works similar to what you describe:

with (this.options) {
    var myVariable = a + 3;  // here a is actually this.options.a
}

However as you can see at the MDN article I linked to there are some cons to using it, because, e.g., of potential ambiguity. In the example above, a could be a property of this.options, or it could be a variable defined elsewhere, and looking just at that block there is no way to tell.

with is not recommended (and is forbidden in strict mode).

There is a safe alternative though: create a variable that references (again in your example) this.options:

var o = this.options;

var myVariable = o.a + 3;

It's not quite as short as typing a on its own, but it's shorter than repeating this.options everywhere.

Upvotes: 1

Joseph
Joseph

Reputation: 119847

You could wrap you object in another object, with attach and detach methods as well as an internal cache to store the actual data object. then have the attach and detach methods provide data as this inside the callback:

function TheObject(data){
    var that = this;

    this.data = data;

    this.attach = function(callback){
        callback.apply(that.data);
    }

}

//wrap the object
var myobj = new TheObject({
    a: 1,
    b: 2
});


myobj.attach(function(){
    //"this" in here is the "data" in the object.
    //this.a
    //this.b
});

Upvotes: 0

Related Questions