Can you bind 'this' in an arrow function?

前端 未结 11 2296
囚心锁ツ
囚心锁ツ 2020-11-22 03:09

I\'ve been experimenting with ES6 for a while now, and I\'ve just come to a slight problem.

I really like using arrow functions, and whenever I can, I use them.

11条回答
  •  心在旅途
    2020-11-22 03:35

    Do ES6 Arrow Functions Really Solve “this” In JavaScript

    The above link explains that arrow functions this doesn't change with bind, call, apply functions.

    It is explained with a very nice example.

    run this in node v4 to see the "expected" behavior,

    this.test = "attached to the module";
    var foo = { test: "attached to an object" };
    foo.method = function(name, cb){ 
        // bind the value of "this" on the method 
        // to try and force it to be what you want 
        this[name] = cb.bind(this); };
    foo.method("bar", () => { console.log(this.test); });
    foo.bar(); 
    

提交回复
热议问题