Javascript Is it possible for one member of an object to access another member of this object without explicit reference to the object itself?

For instance:

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 can be called with a global alias and not mention myObj at all? He realized that if I define him:

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

it will work, but in my case, mentioning myObj unacceptable even inside the function itself (because myObj can be reassigned later, but asGlobal will not change and will continue to work)

+1
source share
3 answers

To call your asGlobal , you will need to do:

 asGlobal.call(myObj); 

ECMAScript 5 introduces the bind() method to provide context for the function. This will 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 can check out Prototype bind , which is almost identical to ECMAScript 5.

+1
source
 var asGlobal = function(){myObj.asMember();} 

If myObj changes to another object, the function will use the last value. If you do not want this, try:

 var asGlobal = function(o){return function(){o.asMember();}}(myObj); 
0
source

Gotcha! Closing works 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
source

Source: https://habr.com/ru/post/1310784/


All Articles