tags:

views:

64

answers:

2

I have code like this

var MyObj = {

    f1 : function(o){ o.onmousedown = MyObj.f2;},
    f2 : function(){ MyObj.f1(); }
}

I would like to know how to refer to MyObj without hardcoding it (i.e. this), so I can change object name without changing the code.

I am interested only in litteral object notation.

EDIT:

I didn't get it right. One of the functions was actually onmousedown event, so this wasn't working in it... This will refer to the object that rised event. I wonder is it still possible to refer to MyObj in such case.

+2  A: 

Use this.

Eg:

var MyObj = {
    f1 : function(){ ... },
    f2 : function(){ this.f1(); }}
Jon Benedicto
A: 

One of the functions was actually onmousedown event, so this wasn't working in it... This will refer to the object that rised event. I wonder is it still possible to refer to MyObj in such case.

One way follows, though it may not be very useful in this case.

var baz = (function(){ // fake a scope
  var foo; // foo will exist in the next statement
  foo = { bar: function(){ return foo } };
  return foo;
})();

The function wrapper, which is executed immediately, acts to keep variables scoped in that block (later versions of JS by Mozilla have improved scoping syntax, but I'm assuming that's not an option). In this simple example, foo is returned and used as the value for baz, but if you were really doing an assignment and didn't care if foo stayed around, then you'd only need the second two lines. But if it were part of a larger expression, then this idiom might come in handy.

Anonymous