【问题标题】:How do I bind the right value of this in javascript class callbacks? [duplicate]如何在 javascript 类回调中绑定 this 的正确值? [复制]
【发布时间】:2017-12-12 07:31:38
【问题描述】:
class SomeClass {
  constructor() {
     this.x = 0;
  }
  getSomething(inputVal) {
   let self = this;
   return new Promise((resolve, reject) => {
    setTimeout(function(){
     if(inputVal){
       self.x = 1;
       resolve();
     }
     else{
       self.x = -1;
       reject();
     }

   }, 10);
 });
}

我必须使用一个名为self 的变量来引用this。这是错误的做法吗?如果没有,我该怎么做?

【问题讨论】:

    标签: javascript ecmascript-6 es6-class


    【解决方案1】:

    这样做有错吗?

    不,显然这种方法没有错,它只是保持对this 对象的引用 的一种方法。

    但是有一些替代方法可以解决这个问题:

    1。使用bind 方法。

    bind() 方法创建一个新函数,在调用该函数时,该函数具有 此关键字设置为提供的值,具有给定的序列 调用新函数时提供的任何参数之前的参数。

    getSomething(inputVal) {
            return new Promise((resolve, reject) => {
                setTimeout(function(){
                    if(inputVal){
                        this.x = 1;
                        resolve();
                    }
                    else{
                        this.x = -1;
                        reject();
                    }
    
                }.bind(this), 10);
            });
     }
    

    2。使用arrow 函数。

    直到arrow 函数,每个new 函数都定义了自己的this 值。

    例如,this 在构造函数的情况下可以是一个新对象。

    function Person(age){
      this.age=age;
      console.log(this);
    }
    let person=new Person(22);

    如果创建的函数可以像obj.getAge() 一样访问,则this 可以指向base 对象。

    let obj={
      getAge:function(){
        console.log(this);
        return 22;
      }
    }
    console.log(obj.getAge());

    arrow 函数不会创建自己的this,它只是使用enclosing 执行contextthis 值。另一方面,arrow 函数使用父作用域的this

    getSomething(inputVal) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (inputVal) {
                    this.x = 1;
                    resolve();
                }
                else {
                    this.x = -1;
                    reject();
                }
    
            }, 10);
        });
    }
    

    【讨论】:

    • . 放在} 旁边时出现语法错误
    • @RanjithRamachandra,我编辑了答案。
    • 我认为你不能在箭头函数中使用 .bind(this)
    • @AmitWagner,是的,很抱歉我的错误。
    • 非常感谢您的详细解释
    【解决方案2】:
    class SomeClass {
        constructor() {
            this.x = 0;
        }
        getSomething(inputVal) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (inputVal) {
                        console.log(this.x);
                        this.x = 1;
                        resolve();
                    }
                    else {
                        this.x = -1;
                        reject();
                    }
    
                }, 10);
            });
        }
    }
    
    const test = new SomeClass();
    test.getSomething(true);
    

    在 setTimeout 中使用箭头函数

    【讨论】:

      猜你喜欢
      • 2021-12-30
      相关资源
      最近更新 更多