如何在ES6的"回调"中使用"this"类?

She*_*pir 0 javascript ecmascript-6 babeljs

我正在使用Babel和ES2015.并且想thiscallback里面使用内部方法.

class baz {
  bar = "xxx";
  foo() {
    x(function() {
      console.log(this.bar);
    });
  }
}

function x(callback) {
  return callback();
}
var y = new baz();
y.foo();
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/dnthehnt/7/ 我收到了

TypeError:这是未定义的

因为据我所知,这指的是回调函数x().作为我使用的解决方案

class baz {
  bar = "xxx";
  foo() {
    var bar = this.bar;//<=====
    x(function() {
      console.log(bar);//<=====
    });
  }
}

function x(callback) {
  return callback();
}
var y = new baz();
y.foo();
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/dnthehnt/6/ 并获得

XXX

这是解决方案,但如果你有大量的代码,它会变得非常混乱和难以编写.有没有更好的解决方案this?或者ES6的任何其他学科使用回调和这个.

jlo*_*wcs 8

查看箭头函数,尤其this是与经典函数相比,箭头函数处理的方式.

class baz {
  constructor() { this.bar = "xxx"; }
  foo() {
    x(() => {
      console.log(this.bar);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

如果在调用x和调用回调之间更改了bar,则使用经典函数的解决方案将无法工作.

这就是你应该如何使用经典功能

class baz {
  constructor() { this.bar = "xxx"; }
  foo() {
    const self = this;
    x(function () {
      console.log(self.bar);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用bind,我想.

class baz {
  constructor() { this.bar = "xxx"; }
  foo() {
    x((function () {
      console.log(this.bar);
    }).bind(this));
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @Shekspir:它与原型没有任何关系.箭头函数没有"this"绑定,因此它们从创建它们的上下文继承它. (3认同)