如何使用“;这个“;在“;回调”;在ES6

How to use "this" of class in "callbacks" in ES6?

本文关键字:ES6 回调 这个 何使用      更新时间:2024-04-16

我正在使用带有ES2015的Babel。并且要在callback内部方法中使用this

class baz {
  bar = "xxx";
  foo() {
    x(function() {
      console.log(this.bar);
    });
  }
}
function x(callback) {
  return callback();
}
var y = new baz();
y.foo();

https://jsfiddle.net/dnthehnt/7/我得到

TypeError:这是未定义的

因为据我所知,这指的是CCD_ 3中的回调函数。作为一种解决方案,我使用

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();

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

xxx

这是一个解决方案,但如果您有大量的代码,就会变得非常混乱和难以编写。有没有更好的解决方案来使用this?或者ES6的任何其他使用回调和此的规程。

研究箭头函数,特别是与经典函数相比,箭头函数处理this的方式。

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

若在对x的调用和对回调的调用之间更改bar,那个么使用经典函数的解决方案将不起作用。

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

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

或者你可以用bind

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