I am reading about prototipcal inheritance. There, and from elsewhere, I am learning this style of avoiding classical inheritance which I am still digesting.
One aspect that still puzzles me, though, is the this
pointer, which is said to cause confusion for many like myself who come from classic OO languages. (If I were to avoid classic inheritance, shouldn't I be avoiding this
as well?
)
After some reading, I realize that the this
pointer is defined not at the time of object/function definition (as in C++) but rather at the site of function call. The this
pointer seems (to me) like a dangling pointer whose target depends on where/how you use it.
Using an example in the linked blog article about extending objects, can someone help explain the following:
Can we avoid using this
or replacing it with explicit object reference?
A related question is, is the this
pointer necessary if I only use prototypical inheritance?
Example from the blog:
It would be nice to combine these two operations into one, ... and extend it with new properties. This operation, called extend, can be implemented as a function:
1 Object.prototype.extend = function (extension) {
2 var hasOwnProperty = Object.hasOwnProperty;
3 var object = Object.create(this);
4
5 for (var property in extension)
6 if (hasOwnProperty.call(extension, property) ||
7 typeof object[property] === "undefined")
8 object[property] = extension[property];
9
10 return object;
11 };
Using the above extend function we can rewrite the code for square as follows:
1 var square = rectangle.extend({
2 create: function (side) {
3 return rectangle.create.call(this, side, side);
4 }
5 });
6
7 var sq = square.create(5);
8
9 alert(sq.area());
Note, this
is used in line 3 of both code segments.