0

i like new arrow ()=>{} syntax and i would like to use it everywhere it's possible. I know that arrow function points to outer this contex. Is there is a way to use arrow function just like normal function? I only need to make this points to the inner of the arrow function.

I need to make this code:

let foo = () => {
 // "this" keyword should point to the inner of that function, not window object
}

works like this code:

function foo() {
 // "this" keyword points to the inner of that class/object/function/whatever-it-calls-fix-me-if-am-i-wrong
}

Is it achievable or i need to stick to the function keyword?

To be more specific i need the this thing to make it working with controllerAs syntax in Angular, but that's not the point. It's rather JS question than AngularJS question.

sdgluck
  • 24,894
  • 8
  • 75
  • 90
hm hm
  • 87
  • 2
  • 9

2 Answers2

1

Is there is a way to use arrow function just like normal function? I only need to make this points to the inner of the arrow function.

Not reasonably, no. Actually, just no, period. :-) Use a function function.

It can't work because arrow functions close over this. Which means there's no way for the caller to set this, which you need in several situations (such as functions on prototypes, callbacks for libs like jQuery that set this, etc.).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • What unreasonable solutions did you think of? If we are allowed to get unreasonable, `toString`+`eval` might do it :-) – Bergi Oct 27 '16 at 18:33
  • @Bergi: The first unreasonable idea I came up with I realized was nonsense. After that, yeah, I was thinking **exactly** `toString` + `eval` (possibly with some munging) and decided Not To Go There. :-) – T.J. Crowder Oct 27 '16 at 18:38
-1

How to Use Arrow functions with libraries that use this

let _self = this;
something.each(function() {
    console.log(_self); 
    console.log(this); 
});

Ref: https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

Korgrue
  • 3,430
  • 1
  • 13
  • 20
  • 2
    Note that the source you're quoting **doesn't** say "How to Use Arrow functions with libraries that use this". It says "Tip: Arrow functions with libraries that use `this`". The tip is basically a warning saying it won't work and saying what to do instead of using an arrow function. Which is why the example you quoted doesn't use an arrow function. – T.J. Crowder Oct 27 '16 at 16:32
  • It absolutely does. Scroll down to "Tip: Arrow functions with libraries that use this" - which happens to be the part of the script I pulled. – Korgrue Oct 31 '16 at 15:54
  • Read the comment above again. – T.J. Crowder Oct 31 '16 at 16:01
  • The question was "Is there is a way to use arrow function just like normal function? " The answer is yes, but you have to cast this as self to avoid scoping conflicts. That script is an example of how to do so by placing that let statement INSIDE your arrow function. – Korgrue Oct 31 '16 at 16:04