Here is the textbook standard way of describing a 'class' or constructor function in JavaScript, straight from the Definitive Guide to JavaScript:
function Rectangle(w,h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return this.width * this.height;
};
I don't like the dangling prototype manipulation here, so I was trying to think of a way to encapsulate the function definition for area inside the constructor. I came up with this, which I did not expect to work:
function Rectangle(w,h) {
this.width = w;
this.height = h;
this.constructor.prototype.area = function() {
return this.width * this.height;
};
}
I didn't expect this to work because the this reference inside the area function should be pointing to the area function itself, so I wouldn't have access to width and height from this. But it turns out I do!
var rect = new Rectangle(2,3);
var area = rect.area(); // great scott! it is 6
Some further testing confirmed that the this reference inside the area function actually was a reference to the object under construction, not the area function itself.
function Rectangle(w,h) {
this.width = w;
this.height = h;
var me = this;
this.constructor.prototype.whatever = function() {
if (this === me) { alert ('this is not what you think');}
};
}
Turns out the alert pops up, and this is exactly the object under construction. So what is going on here? Why is this not the this I expect it to be?