在 constructor 中 bind this 的优点

class A {
  foo = () => {
    console.log(this.foo);
  };
}

class B {
  constructor() {
    this.foo = this.foo.bind(this);
  }
  foo() {
    console.log(this.foo);
  }
}

题目:为什么在react项目中,class B绑定事件的方式会比第一种好?

分析编译完成的代码

看一下typescript编译完的代码:

"use strict";
var A = /** @class */ (function() {
  function A() {
    var _this = this;
    this.foo = function() {
      console.log(_this.foo);
    };
  }
  return A;
})();
var B = /** @class */ (function() {
  function B() {
    this.foo = this.foo.bind(this);
  }
  B.prototype.foo = function() {
    console.log(this.foo);
  };
  return B;
})();

假设组件A被复用多份,那么每个实例对象都会重新定义开辟foo方法需要的内存。

打开 chrome 调试测试

得出结论

class B 这种声明方式每个对象所占的内存小了。在组件多次复用之后会节省内存。

TODO

但是我们也看到整个页面所占的内存并没有很大变化?稳定之后都是 10.3M。需要进一步探索

答案: 由于测试的时候只生成 100 个对象,数据样本太小,得出结论不准确,现生成 10000 条数据测试发现已经相差快 1M 内存差距了。

测试代码

测试代码路径: