【问题标题】:this/self in es6 class [duplicate]es6 类中的 this/self [重复]
【发布时间】:2026-01-24 03:00:01
【问题描述】:

当我从回调中调用 es6 类的方法时,我不能再将 this 作为我的对象:

class store{
  constructor(){
    this.value = 10;
  };

  printValue(self){
    console.log(this);
    console.log(self);//the value that I want print
  };
};

class undefinedClass{
  constructor(store){
    this.store = store;
  };

  storeQuery(){
    let ff = this.store.printValue;
    setTimeout(ff, 300, this.store);
  };
};

let i = new store();
let b = new undefinedClass(i);
b.storeQuery();

当我调用 b.storeQuery() 时,我想要打印的值是第二个。 有没有更优雅的方式来做到这一点?

【问题讨论】:

标签: javascript ecmascript-6


【解决方案1】:

正如@alex 所说,.bind

文档是here

class store{
  constructor(){
    this.value = 10;
  };

  printValue(){
   
    console.log(this.value);//the value that I want print
  };
};

class undefinedClass{
  constructor(store){
    this.store = store;
  };

  storeQuery(){
    setTimeout(this.store.printValue.bind(this.store), 300);
  };
};


let i = new store();
let b = new undefinedClass(i);

 
b.storeQuery();

【讨论】:

    【解决方案2】:

    当你在 JavaScript 中使用一个对象的函数引用时,它会失去它被设置为该对象的 ThisBinding。

    您可以使用 Function.prototype.bind() 将 ThisBinding 绑定到任何东西。

    在这种情况下,您可以使用 ff.bind(this.store) 之类的东西。

    【讨论】:

    • alex -- 请在此处查看我的评论:*.com/questions/36722798/… 你如何解决这个问题?
    • 或者使用箭头函数。 printValue 无论如何都需要一个参数。