I have a function defined on another function, like so
function Test(message) {
this.message = message;
}
Test.prototype.print = function() {
console.log(this.message);
}
Test.prototype.print.polite = function() {
console.log(this.message + ', please.');
}
var x = new Test('hello world');
x.print();
x.print.polite();
x.print() prints 'hello world' as expected, but x.print.polite() prints 'undefined, please', as opposed to 'hello world, please'.
I understand that this is because the context passed to the print.polite function is the print function. Is there, however, a way to access the 'this' of print from print.polite, short of explicitly adding it as a parameter? I'd like to retain the invocation semantic of print.polite(), instead of making it printPolite().
I'm fairly new to JavaScript, so I apologize if this is an inane question.
Edit
Based on the suggestions, I've modified my code like so, and it seems to work.
function Test(message) {
this.message = message;
this.print.that = this;
}
Test.prototype.print.polite = function() {
console.log(this.that.message + ', please.');
}
Like you pointed out, though, it is a rather hacky solution. Isn't there a more elegant way to do this?