As the title (sort of) explains, when I’m prototyping in JS, and I need to reference another function of the object, should I access the protoypal version of it, or the local variables version? Is there any (major) overhead issues involved with either one?
//starting off
Foo = function(){ }
Foo.prototype.ShowMessage = function(msg){
alert(msg);
}
//method 1
Foo.prototype.Validate = function(msg){
//some validation stuff...
if(!Valid){
this.ShowMessage("Please check your inputs, there seems to be a problem with them.");
}
}
//method 2
Foo.prototype.Validate = function(msg){
//some validation stuff...
if(!Valid){
Foo.prototype.ShowMessage("Please check your inputs, there seems to be a problem with them.");
}
}
I’d prefer method 1, purely because it’s easier to type this, than Foo.prototype, but does it matter performance wise which one? Or am I just MoM-ing this?
You should definitely use
The second version simply would not work properly at all. Why? Because that invocation of
showMessagewould result in its “this” variable pointing to that prototype object and not the instance. That would almost certainly not be what you want.