Javascript: access to the correct scope under "apply" (...)

This is a very old problem, but I don't seem to understand how this will affect the other solutions presented here.

I have an object

function ObjA() { var a = 1; this.methodA = function() { alert(a); } } 

which is created as

 var myObjA = new ObjA(); 

Subsequently, I assign the methodA function as a handler function in the external Javascript Framework, which calls it using the apply(...) method.

When the external framework executes my methodA , this belongs to the framework function that calls my method.

Since I cannot change the method of calling my method, how can I regain access to the private variable a ?

My research tells me that closing may be what I'm looking for.

+4
source share
4 answers

You already have a closure. When methodA called methodA access to a will work fine.

Object properties are different things for areas. You use scopes to implement something that behaves like "private members in other languages, but a is a local variable in the parent scope, not a member of myObjA (private or otherwise). Having a function like methodA preserves access to variables in their parent area, which means closure.

What areas that you can access are fixed: you can always access variables in your parent areas, but you call them back, and you cannot call a function with different areas before those that it had when it was defined .

Since a not a property of this , it does not matter that this not preserved when you call it. If you need to get the correct this , then yes, you will need one more work, or using another closure on myObjA :

 onclick= function() { myObjA.methodA(); }; 

or using the # bind Function :

 onclick= myObjA.methodA.bind(myObjA); 
+2
source

Yes you are right. Instead of a method reference

  var myObjA = new ObjA(); libraryCallback = myObjA.methodA 

pass closure

  libraryCallback = function() { myObjA.methodA() } 
+1
source

If you are using the jQuery javascript framework, the easiest way is to use a proxy :

 $('a').click($.proxy(myObjA, 'methodA')); 
0
source

I would do this:

 function ObjA() { this.a = 1; this.methodA = function() { alert(this.a); } } function bindMethod(f, o) { return function(){ return f.apply(o, arguments); } } var myObjA = new ObjA(); myObjA.methodA = bindMethod(myObjA.methodA, myObjA); ... 

Where bindMethod binds the methodA method always, like the myObjA method, still passing any arguments that function() {myObjA.methodA()} does not execute.

0
source

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


All Articles