10 月 2018

关于Javascript中类成员函数中内嵌函数的this闭包问题

之前写CocosLua和CocosJS时经常会遇到类成员函数中调用内嵌函数时的this传递问题,最近发现Javascript中可以通过使用箭头函数简化这个this的闭包问题,先给出测试代码:

class clsTest {
  constructor(var1) {
    this._var1 = var1;
  }

  foo() {
    console.log("1111", this._var1);

    (() => {
      console.log("2222", this._var1);
    })();

    (function() {
      console.log("3333", this);
    })();

    let self = this;
    (function() {
      console.log("4444", self._var1);
    })();
  }
}

let objTest = new clsTest(10);
objTest.foo();

JSFiddle:https://jsfiddle.net/u0yconbg/2/

为了简化示例代码,内嵌函数都写成了自调用的形式,可见333时的内嵌函数调用this是undefined,所以4444时在调用函数前声明了self用于闭包进内嵌函数访问this,(Lua中一般是local this = self),而2222的内嵌函数是通过箭头方式声明的,可见log中成功输出了clsTest类对象的_var1成员变量值,也就是说this被自动传递了,为此特意查了下文档:

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

来自:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions