I was trying out the below question in ES6 learning material
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())
At first I thought the result printed to be 314.1592653589793
but turns out the result printed is NaN
. Which mean that the getArea()
function does not have access to this
. Why does the function do not have access to this
while de-structuring the Object ?
Destructuring is just syntactic sugar for assigning object properties to variables, so the following line:
let {radius, getArea, getCircumference} = circle;
is equivalent to:
let radius = circle.radius;
let getArea = circle.getArea;
let getCircumference = circle.getCircumference;
Here getArea
is just a reference to the base-function, which doesn't include the context of circle
. So your getArea
variable may as well just be declared like so:
const getArea = function() {
return Math.PI * this.radius * this.radius;
}
console.log(getArea()); // NaN
The this
in the function is thus determined by the calling context of getArea
when it is actually called. Since no context is provided in the above example, it defaults to the global object of the window
.
You can specify the this
of the getArea()
function later on though by using .call()
:
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.call(circle)); // 314.1592653589793