ES6 函数在解构对象时无权访问“this”

Pra*_*nth 2 javascript ecmascript-6 object-destructuring

我在 ES6 学习材料中尝试了以下问题

const circle = {
  radius: 10,
  color: 'orange',
  getArea: function() {
    return Math.PI * this.radius * this.radius;
  },
  getCircumference: function() {
    return 2 * Math.PI * this.radius;
  }
};

let {radius, getArea, getCircumference} = circle;
console.log(getArea())
Run Code Online (Sandbox Code Playgroud)

起初我以为打印的结果是,314.1592653589793但结果打印的结果是NaN. 这意味着该getArea()函数无权访问this. 为什么this在解构 Object 时该函数无权访问?

Nic*_*ons 7

解构只是将对象属性分配给变量的语法糖,因此以下行:

let {radius, getArea, getCircumference} = circle;
Run Code Online (Sandbox Code Playgroud)

相当于:

let radius = circle.radius;
let getArea = circle.getArea;
let getCircumference = circle.getCircumference;
Run Code Online (Sandbox Code Playgroud)

这里getArea只是对基本函数的引用,不包括circle. 所以你的getArea变量也可以像这样声明:

let {radius, getArea, getCircumference} = circle;
Run Code Online (Sandbox Code Playgroud)

this在功能因此被的调用上下文确定getArea时,它实际上是。由于上例中没有提供上下文,因此默认为window.

您可以指定this的的getArea()功能以后,虽然使用.call()

let radius = circle.radius;
let getArea = circle.getArea;
let getCircumference = circle.getCircumference;
Run Code Online (Sandbox Code Playgroud)