JS类-在promise中未定义'this'

有一个类,如果我要填充“绞盘”中定义的此类绞盘的类在内部,则为该类。

 class ClassA {

   constructor(){
      ...
      this.place = [];
   }

   fillUp() {
      fetch(path)
        .then(function(response) {
          return response.json();
        }).then(function(result) {

         this.place.push({"result":result})
        })
    }
 }
inst = new ClassA();   
inst.fillUp();

结果是我收到此错误:TypeError:无法读取未定义的属性“ place”。 问题可能在哪里?

iseehr 回答:JS类-在promise中未定义'this'

javascript中的

this很奇怪。根据在对象上调用代码/函数的方式,它可能会返回您未期望的值。如果您使用的是现代javascript,则应使用短箭头表示法。这将保留绑定到this的对象。否则,您将不得不在引用.bind(this)的函数中添加this

fetch(path)
    .then((response)=>{
        return response.json();
    }).then((result)=>{
        this.place.push({"result":result})
    })

,

使用箭头功能。

 class ClassA {

   constructor(){
      ...
      this.place = [];
   }

   fillUp = () => {
      fetch(path)
        .then(function(response) {
          return response.json();
        }).then(function(result) {

         this.place.push({"result":result})
        })
    }
 }
inst = new ClassA();   
inst.fillUp();
,

promise处理程序是具有不同this值的不同函数。

要使this内部相等,可以使用箭头函数,这些箭头函数从定义的地方继承this

class ClassA {

   constructor(){
      ...
      this.place = [];
   }

   fillUp() {
      fetch(path)
        .then(response =>  response.json())
        .then(result => {
          this.place.push({"result":result})
        })
      }
    }
inst = new ClassA();   
inst.fillUp();

或者,.bind()函数:

class ClassA {

   constructor(){
      ...
      this.place = [];
   }

   fillUp() {
      fetch(path)
        .then(function(response) {
          response.json()
        })
        .then((function(result) {
          this.place.push({"result":result})
        }).bind(this))
      }
    }
inst = new ClassA();   
inst.fillUp();
,

您可以通过在回调中使用arrow function expression来尝试push进入数组来解决问题。使用典型函数表达式的问题在于它创建了自己与this关键字的绑定。另一方面,箭头功能:

  

箭头功能没有自己的this。的this值   使用封闭的词汇范围;箭头功能遵循正常   可变查找规则。因此,在搜索this时,   当前范围内的箭头功能最终会找到this   从其封闭范围。

因此,如果您在回调中使用箭头函数,该函数将从其封闭范围(即this对象)中提取ClassA

以下是其工作方式的演示:

const mockFetch = new Promise((resolve,reject) => {
  console.log('Fetching data..please wait..')
  setTimeout(() => resolve({
    json: () => '{ data: \'Some response data\'}'
  }),1500)
});


class ClassA {
  constructor() {
    this.place = [];
  }

  fillUp() {
    mockFetch.then(function(response) {
      return response.json();
    }).then(result => {
      this.place.push({
        "result": result
      });
      console.log(this.place);
    })
  }
}

inst = new ClassA();
inst.fillUp();

,
.then((result) => {
 this.place.push({"result":result})
})

很棒。比你!

本文链接:https://www.f2er.com/3049796.html

大家都在问