Accessing a container object inside event functions

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 access MyObj without hardcoding it (i.e. this), so I can change the object name without changing the code.

I am only interested in the designation of the elbow object.

EDIT :

I didn't get it. One of the functions was actually the onmousedown event, so it didn't work in it ... This would refer to the object where the event happened. I wonder if it is possible to reference MyObj in this case.

0


a source to share


2 answers


One of the functions was actually onmousedown, so it wasn't working in it ... That would mean the object that augmented the event. interestingly you can still refer to MyObj in this case.

This is followed by one of the methods, although in this case it may not be very useful.



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

      

The functional wrapper, which is executed immediately, acts to store the variables covered by this block (later versions of JS from Mozilla have improved syntax for the definition, but I assume this is not an option). This simple example returns foo

and is used as the value for baz

, but if you are really doing the job and don't care if there is left foo

then you only need two two lines.But if that were part of a larger expression, then this idiom might come in handy.

0


a source


Use this

.

For instance:



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

      

+2


a source







All Articles