question 3
Frankly, i think 【the this keyword refers to its definition surrounding scope】 is more suitable than 【the this keyword refers to its current surrounding scope】
for example:
shape.perimeter.call(shape) still return NaN,but its current surrounding scope this point shape.
Good issue :+1:
Yes you can bind, call or apply context to functions but I think adding definition will complicate the context of this question. Later in that question, surrounding scope is written without current so maybe it can be removed?
Do you mean its definition's surrounding scope?
Yes
use babel to translate, such as :
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius
};
TO
"use strict";
var _this = void 0;
var shape = {
radius: 10,
diameter: function diameter() {
return this.radius * 2;
},
perimeter: function perimeter() {
return 2 * Math.PI * _this.radius;
}
};
We can see that arrow function's this point to it's definition's surrounding scope.
Maybe I prefer to use this way. class shape { radius = 10; perimeter = () => 2 * Math.PI * this.radius; } const newShape = new shape; console.log(newShape.perimeter());
@shuofenghao
class shape {
radius = 10;
perimeter = () => 2 * Math.PI * this.radius;
}
const newShape = new shape;
console.log(newShape.perimeter());
a = newShape.perimeter
a()
Above example also work, but not correct for normal function.