I'm new to Javascript and just want to make sure I'm understanding how it handles the this
keyword, since... well, it seems like it's pretty messy. I've checked out similar questions on StackOverflow and want to make sure I'm not moving forward with the wrong idea.
So I'm defining a class like so, and want to process every point received 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 that is simply passing a pointer to the prototype function, which means this
in addPoint
refers to the global object.
Then I tried:
ptList.forEach(function(p) { this.addPoint(p); });
but I can't, because this
refers to the global scope as soon as I enter that internal function (it no longer refers to the Curve
object being constructed), so addPoint
is undefined.
The way to get around that is to make a variable that refers to this
in a scope I can still talk to in the subfunction:
var _this = this;
ptList.forEach(function(p) { _this.addPoint(p); });
And this finally works (but looks really weird to someone without JS experience). But then I found out about the bind
function, which lets me not define a trivial function wrapper:
ptList.forEach(this.addPoint.bind(this));
and it seems like, finally, this is the best and most concise way to do it, even thought it looks silly. Without the bind
function, addPoint
has no understanding of which object it was called on, and without the first this
, I can't even find my addPoint
function.
Is there a better way to do this seemingly simple thing, or is that last line of code the recommended way?