es6 Class 的 this 指向

Class 的 this 指向

ES6 类的方法内部如果含有this,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。

 
 
  1. class Logger {
  2. printName(name = 'there') {
  3. this.print(`Hello ${name}`);
  4. }
  5. print(text) {
  6. console.log(text);
  7. }
  8. }
  9. const logger = new Logger();
  10. const { printName } = logger;
  11. printName(); // TypeError: Cannot read property 'print' of undefined

上面代码中,printName方法中的this,默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境,因为找不到print方法而导致报错。

一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到print方法了。

 
 
  1. class Logger {
  2. constructor() {
  3. this.printName = this.printName.bind(this);
  4. }
  5. // ...
  6. }

另一种解决方法是使用箭头函数。

 
 
  1. class Logger {
  2. constructor() {
  3. this.printName = (name = 'there') => {
  4. this.print(`Hello ${name}`);
  5. };
  6. }
  7. // ...
  8. }

还有一种解决方法是使用Proxy,获取方法的时候,自动绑定this

 
 
  1. function selfish (target) {
  2. const cache = new WeakMap();
  3. const handler = {
  4. get (target, key) {
  5. const value = Reflect.get(target, key);
  6. if (typeof value !== 'function') {
  7. return value;
  8. }
  9. if (!cache.has(value)) {
  10. cache.set(value, value.bind(target));
  11. }
  12. return cache.get(value);
  13. }
  14. };
  15. const proxy = new Proxy(target, handler);
  16. return proxy;
  17. }
  18. const logger = selfish(new Logger());
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值