开发者

javascript. is it posible for one member of an object to access another member of that object without explicit reference to the object itself?

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 al开发者_如何学Gol? 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)


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.


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);


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(); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜