Note that there are some explanatory texts on larger screens.

plurals
  1. POConstructor inheritance; what am I not getting here?
    primarykey
    data
    text
    <p>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?</p> <pre><code>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' </code></pre> <p>What I'm expecting is that when I assign <code>test</code> the property <code>this.v</code> is set to "bar". As far as I understand JS prototypical inheritance setting <code>B</code>'s prototype to <code>A</code>'s means everything in <code>B</code> is overwritten. I would expect then that it's constructor is overwritten, and that calling <code>new B('bar')</code> would execute <code>A</code>'s constructor with the parameter "bar".</p> <p>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:</p> <pre><code>// constructors from above B.prototype.yell = function(){ alert('hello world'); } var test1 = new B('bar'), test2 = new B('spam'), test3 = new B('eggs'); </code></pre> <p>...so that the JS objects I'm creating follow a similar inheritance pattern to standard OOP and therefore <code>B</code> would inherit <code>A</code>'s constructor and methods.</p> <p><strong>Edit:</strong></p> <p>After reading the comments, I believe a better question would be to ask how would one overwrite <code>B</code>'s constructor with <code>A</code>'s?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload