JavaScript defines Object.prototype
as a way to define methods or properties for class-like objects.
A big problem that exists when using Object.prototype
is the incorrect behavior when a method is invoked via a callback as this
will have the invoking context.
function Foo() {}
Foo.prototype.resize() {
console.log(this);
}
var foo = new Foo();
window.on('resize', foo.resize);
So to work around this limitation we can do the following.
function Foo2() {
function resize() {
console.log(self);
}
var self = this;
this.resize = resize;
}
var foo2 = new Foo2();
window.on('resize', foo2.resize);
Given the above situation, it seems like it's better to always define class-like objects in example 2.
Thus, when should we use the Object.prototype
facilities? I mean, you cannot know a priori how your methods will be called, and most certainly you would want the correct this
context reference when invoked.
Supporting context: I thought of this question as it seems like you are creating instance methods using Object.prototype
. However, as illustrated, you are not. You are simply creating methods that have no "real" connection to their instance. Hence the need to use closure to create an instance-bound method. Furthermore, this question was thought of after reading this excellent explanation of this
.