views:

298

answers:

1
 function main()
{
  this.one = 1;
}

main.prototype = {
  display: function()
  {
    console.log(this.one);
    return this;
  }
};

function addition() {
  main.call(this);
}

addition.prototype = new main;
addition.prototype.constructor = addition;

addition.prototype = {
  add: function(x) {
    this.one += x;
    return this;
  }
};

// addition.prototype.add = function(x)
// {
//   this.one += x;
//   return this;   
// }

display = new addition;
display.add(3).add(5).display();

If I replace the commented addition.prototype.add with the addition.prototype above it, it will work fine, logging '9'. Otherwise, running the above snippet will result in "display.add(3).add(5).display is not a function" in Firebug 1.4, Firefox 3.5.

What's the difference between the 2 segments? I've always thought they are the same, please advise on the difference, or/and how I could make it work with the commented codes.

Or at least point me to the keywords I should google for, I've tried looking in vains for hours.

Thanks.

+3  A: 

It looks like you're overwriting the parent's (main)'s prototype with your code:

addition.prototype = {
  add: function(x) {
    this.one += x;
    return this;
  }
};

addition.prototype is now a new object because you just assigned to it.

When you do:

addition.prototype.add = function(x) {
 this.one += x;
 return this;   
}

You're adding a property to addition.prototype, so you keep main's inherited display() function.

Btw, where are you getting this code from? It's one of the more confusing examples of inheritance in JavaScript that I've seen.

Chu Yeow
Ah, thanks! Now it makes sense.I can't recall the first site that talked about this, but one of the other sites is http://www.cristiandarie.ro/asp-ajax/JavaScriptPrototypeInheritance.htmlWow, among all the sites I found, this seems to be the simplest to follow as I'm not sure what's the best practice, do you have any sites to recommend for best practice of such prototypical inheritance?
I believe that Chu is correct: addition.prototype = ... is definitely severing your pointer the main.prototype you created earlier so display is no longer available. I also agree that the example is odd. First of all, draco PLEASE use upper case letters for function constructor's to signify to others that they must use 'new' when calling. If I accidently say: m = main() I've just clobbered the global namespace! There are a bunch of other real issues with the classical pattern (mangled as it is). Please look at my examples here: http://github.com/roblevintennis/Testing-and-Debugging-JavaScript
Rob