ES6 - 重新绑定类方法

时间:2017-04-05 18:47:19

标签: javascript binding ecmascript-6 es6-class

我目前正在尝试ES6课程,而且我遇到过这个我不完全理解的问题。我想通过给它一个函数来创建一个初始化的类。该类有一个运行该函数的方法,但具有任何给定的上下文。我尝试过这样的事情:

class MyClass {
  constructor(action) {
    this.action = action;
  }
  run(context, n) {
    this.action.call(context, n);
  }
}

// instantiate my class with a function that uses 'this' to log a given number
let a = new MyClass((n) => {
  this.log(n);
})

// calls the run method of my class, giving console as the context and 1 as n.
a.run(console, 1);

我希望这段代码会导致1被记录到控制台。但是,我得到了一个TypeError。

我认为我误解了关于类和上下文绑定如何在ES6中工作的问题。任何人都可以帮助我吗?

修改

这对于箭头函数和函数声明之间的区别是一个很好的教训。谢谢你的答案!

2 个答案:

答案 0 :(得分:0)

问题源于箭头功能的工作原理。

箭头函数将public void verifyAndAcceptAlert(WebDriver driver){ try{ WebDriverWait wait = new WebDriverWait(driver,10); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); alert.accept(); } catch(Exception e){ //to do something } } 绑定到它们的词汇环境:

this

要修复代码,只需使用常规函数表达式定义let obj = { a: 1, init() { this.log = () => console.log(this.a); } }; obj.init(); obj.log(); // And the `this` value cannot be changed obj.log.call({ a: 500 });

action

答案 1 :(得分:0)

你使用箭头功能打破了事情

let a = new MyClass((n) => {
  this.log(n);
});

相同
let _this = this;
let a = new MyClass(function(n) {
  _this.log(n);
});

因为箭头函数会将范围查找到其父级。你应该使用正常的函数

let a = new MyClass(function(n) {
  this.log(n);
});