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) {
}
}
Curve.prototype.addPoint = function(p) {
this.pts.push(p);
}
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.
, , , ?