Class function call in forEach: how Javascript handles the keyword "this"

I am new to Javascript and just want to make sure that I understand how it handles the keyword this, since ... well, it looks like it's pretty dirty. I checked similar questions in StackOverflow and want to make sure that I am not progressing with the wrong idea.

So, I define such a class and I want to process every point obtained in the constructor.

function Curve(ptList) {
  this.pts = [];

  if(ptList.length > 2) {
    // I want to call "addPoint" for every item in ptList right here
  }
}

Curve.prototype.addPoint = function(p) { 
  this.pts.push(p);
  /* some more processing here */ 
}

So, initially I thought I could just do:

ptList.forEach(this.addPoint);

but I can't, because it's just passing a pointer to a prototype function, which means that thisin addPointrefers to a global object.

Then I tried:

ptList.forEach(function(p) { this.addPoint(p); });

, this , ( Curve), addPoint - undefined.

, , this , :

var _this = this;
ptList.forEach(function(p) { _this.addPoint(p); });

, , ( -, JS). bind, :

ptList.forEach(this.addPoint.bind(this));

, , , , , . bind addPoint , , this addPoint.

, , , ?

+2
2

forEach() , map() filter(), thisArg .

this ", :

ptList.forEach(this.addPoint, this);

, ( name self), .bind() . , - :

function Curve(ptList) {
  var pts = [];
  function addPoint(p) {
      pts.push(p);
  }

  if(ptList.length > 2) {
    ptList.forEach(addPoint);
  }

  this.addPoint = addPoint;
}

, , ( , ), JavaScript , 't this , , , CPU ( ).

+4

var that = this. JavaScript , , . - ptList.forEach(this.addPoint.bind(this)) .

'var that = this;' JavaScript?

0

All Articles