javascript-questions icon indicating copy to clipboard operation
javascript-questions copied to clipboard

question 3

Open aizuyan opened this issue 6 years ago • 6 comments

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.

aizuyan avatar Jun 18 '19 02:06 aizuyan

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?

A1rPun avatar Jun 19 '19 19:06 A1rPun

Do you mean its definition's surrounding scope?

lydiahallie avatar Jun 23 '19 21:06 lydiahallie

Yes

aizuyan avatar Jun 24 '19 02:06 aizuyan

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.

aizuyan avatar Jul 23 '19 02:07 aizuyan

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 avatar Jul 23 '19 02:07 shuofenghao

@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.

aizuyan avatar Jul 23 '19 02:07 aizuyan