I'm trying to understand inheritance in Javascript, but this code (tested in Firebug) doesn't work the way I'm expecting. What am I not understanding about it?
var A = function(v){
this.v = v || 'foo';
}
A.prototype.shout = function(){ alert(this.v); }
var B = function(){};
B.prototype = new A;
var test = new B('bar')
test.shout() // returns 'foo'
What I'm expecting is that when I assign test
the property this.v
is set to "bar". As far as I understand JS prototypical inheritance setting B
's prototype to A
's means everything in B
is overwritten. I would expect then that it's constructor is overwritten, and that calling new B('bar')
would execute A
's constructor with the parameter "bar".
If my understanding is incorrect, could someone please correct me. It would also be good to find the solution to what I'm looking to do:
// constructors from above
B.prototype.yell = function(){ alert('hello world'); }
var test1 = new B('bar'), test2 = new B('spam'), test3 = new B('eggs');
...so that the JS objects I'm creating follow a similar inheritance pattern to standard OOP and therefore B
would inherit A
's constructor and methods.
Edit:
After reading the comments, I believe a better question would be to ask how would one overwrite B
's constructor with A
's?