views:

49

answers:

3

For example:

var myObj={

  myValue="hola",

  asMember=function(){ alert( this.myValue ); }

};


myObj.asMember(); // will work fine

var asGlobal=myObj.asMember; // global alias for that member function
asGlobal(); // won't work in javascript (will work in AS3, but i need js now)

So the question is, can I rewrite asMember so that it could be called by global alias and without mentioning myObj at all? It's understood that if I define it:

asMember=function(){ alert( myObj.myValue ); }

it will work, but in my case, mentioning myObj is not acceptable even inside the function itself (because myObj may be reassigned later, but asGlobal won't change and should keep working)

A: 
var asGlobal = function(){myObj.asMember();}

If myObj changes to a different object, the function will use the latest value. If you don't want this, try:

var asGlobal = function(o){return function(){o.asMember();}}(myObj);
Matthew Flaschen
no `myObj` at all please. It will change
joox
nono. `asGlobal` MUST be just an alias for `asMethod`. The only thing I am allowed to do is change `asMethod` so that it somehow knows that it is a member of `myObj`
joox
+1  A: 

To invoke your asGlobal, you would need to do:

asGlobal.call(myObj);

ECMAScript 5 will introduce the bind() method for enforcing the context of a function. This would allow you to do the following:

var asGlobal = myObj.asMember.bind(myObj);
asGlobal();

However bind() is not yet supported in current browsers, as far as I know. In the meantime, you may want to check out Prototype's bind implementation, which is virtually identical to the ECMAScript 5 method.

Daniel Vassallo
A: 

Gotcha! Closures do well

function myObj(){

  var myValue="hola";

  return{
    asMember:function(){ alert( myValue ); },
    anotherMemer:function(){/* ... */}
  }

};

var temp=myObj();

var asGlobal=temp.asMember; // global alias for that member function
asGlobal(); 
joox