访问ES6中的Object.keys内部[重复]

问题描述 投票:2回答:4

假设我有以下代码:

class Test {
  constructor(obj) {
    this.obj = obj
  }

  change() {
    Object.keys(this.obj).forEach(function(name, index) {
      alert(this.obj[name])
    })
  }

}

objct = {
  n1: 1,
  n2: 2
}

var test = new Test(objct)
test.change()

但是,当我运行它时,我收到以下错误:

未捕获的TypeError:无法读取未定义的属性'obj'

我相信这意味着this在对象键功能中未定义。如何访问Object键和forloop中的this.obj

根据这个answer,我可以使用map,但我需要在forloop中的属性名称和数组index。这里是代码的fiddle,如果它可以帮助你。谢谢!!!

javascript ecmascript-6
4个回答
6
投票

那是因为你传递给this的函数的函数上下文(forEach())现在是window而且它不再是你的Test实例。

如果您将使用箭头函数,您将能够保留词法范围,并且您的this将指向当前(Test)实例:

Object.keys(this.obj).forEach((name, index) =>
{
    alert(this.obj[name])
});

MDN


4
投票

Javascript中的经典范围课程。

有两种方法可以做到这一点:

使用bind()将forEach的范围绑定到父函数

change() {
  Object.keys(this.obj).forEach(function(name, index) {
    alert(this.obj[name])
  }.bind(this))
  }

使用=>,这是将forEach的范围绑定到父函数的另一种方法

change() {
  Object.keys(this.obj).forEach((name, index) => {
    alert(this.obj[name])
  })
  }

4
投票

this指的是函数的当前上下文,因此在你的例子中this.objobj回调的上下文中寻找forEach。您可以通过保持对当前上下文的引用来解决此问题,即this或使用箭头函数。

老方法:在这个解决方案中,我们在变量self中保留对当前上下文的引用

class Test {
  constructor(obj){
    this.obj = obj
  }

  change() {
    var self = this
    Object.keys(this.obj).forEach(function (name, index) {
    alert(self.obj[name])
  })
  }

}

objct = {
  n1: 1,
  n2: 2
}

var test = new Test(objct)
test.change()

首选或简写解决方案:使用箭头功能

class Test {
  constructor(obj){
    this.obj = obj
  }

  change() {
  Object.keys(this.obj).forEach((name, index) => {
    alert(this.obj[name])
  })
  }

}

objct = {
        n1: 1,
      n2:2
}

var test = new Test(objct)
test.change()

1
投票

匿名函数不绑定到上下文,因此它们无权访问this;但箭头功能是。所以请改用它。

class Test {
  constructor(obj) {
    this.obj = obj
  }

  change() {
    Object.keys(this.obj).forEach((name, index) => {
      alert(this.obj[name])
    })
  }

}

objct = {
  n1: 1,
  n2: 2
}

var test = new Test(objct)
test.change()
© www.soinside.com 2019 - 2024. All rights reserved.