views:

30

answers:

2

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?

+3  A: 

You should definitely use

this.showMessage("msg");

The second version simply would not work properly at all. Why? Because that invocation of showMessage would result in its "this" variable pointing to that prototype object and not the instance. That would almost certainly not be what you want.

Pointy
Though in this case, the function doesn't use 'this'. But there's no advantage doing it that way, and as Pointy says in most cases it doesn't do what you want.
Colin Fine
Right; it's just a general matter of coding things conventionally. There might be *rare* cases where you'd really want or need to explicitly call the prototype function, but that'd represent a fairly exotic situation.
Pointy
A: 

In case you want to have a instance method you should use this.* reference. Otherwise if you want to have a kind of class method you can use the following:

//starting off
Foo = function() {
};

Foo.prototype.ShowMessage = function(msg) {
    alert("Instance message: " + msg);
};

Foo.ShowMessage = function(msg) {
    alert("Class message: " + msg);
};

Foo.prototype.Validate = function(msg) {
    //some validation stuff...
    if (!Valid) {
        this.ShowMessage("Please check your inputs, there seems to be a problem with them.");
        Foo.ShowMessage("Please check your inputs, there seems to be a problem with them.");
    }
};
fantactuka