0

Using groovy , you can run closure like following :

  instanceB.methodB({
          methodA(3);
          methodA(3);
  }); 
  //---- methodB definition 
  class B{
       def methodB(Closure c){
             c.delegate=new A(); //!!!---The question is about this "delegate" in JS
             c.call();
       }

  }

As you may note, we call directly methodA inside closure without this (this.methodA()) . This is because of this instruction c.delegate=new A() : Therefore, All methods of new A() can be called there .

My question :

How to make this works with Javascript using Arrow-functions : Either ES6 or ES7 .

Does Arrow-functions has something like delegate ?

Pseudo code :

instanceB.methodB(()=>{
     methodA(3); 
     methodA(4);
});
class B{
     methodB(arrow){
         arrow.delegate=new A(); // What's the right way, if any ?
         arrow.call();  
     }

}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254

1 Answers1

2

No, arrow functions do not have such a feature and neither have any other functions.

Scope is lexically determined in JS, i.e. it depends on where you declare your functions, and you cannot inject anything or modify it from outside.

Your best bet might be the with statement, although you have to put it inside your (arrow) function not at the call site, or eval.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375