0

The prototype is an object that is inherited? by all instances of the object, like child in my following example.

It has to be an instance of the parent, else parent's prototype will not get inherited?

In this case, the goal is to create a separate array, which is inherited from parent, for each instance of child.

I am unsure how to achieve that exactly. I know of extend.

Is the extend method simply copying prototypes over to a new object and applying the new methods onto it as well?

My code example + jsfiddle:

function parent(){
}

parent.prototype.arr = []; 
parent.prototype.add = function(item){
    this.arr.push(item);
}
parent.prototype.show = function(){

    for(var i = 0; i < this.arr.length; ++i){
        $('body').append(this.arr[i]);
    }
}


function child(childname){
    this.add(childname); 
}
child.prototype = new parent();


var child1 = new child('child1');
var child2 = new child('child2');

child2.show();//this should only show child2? 
alotofquestions
  • 164
  • 1
  • 2
  • 12
  • http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks Jan 31 '14 at 01:30
  • 1
    `parent.prototype.arr = []; ` This is always wrong; you only ever have one instance. – SLaks Jan 31 '14 at 01:30
  • `child.prototype = new parent();` does nothing useful. Creating a public *prototype* property of an Object is entirely different to the private [`[[Prototype]]`](http://ecma-international.org/ecma-262/5.1/#sec-8.6.2) inhertited from its constructor. – RobG Jan 31 '14 at 01:42
  • http://aaditmshah.github.io/why-prototypal-inheritance-matters – Aadit M Shah Jan 31 '14 at 02:21
  • You have a lot of links and documentation to read. I have created the following answer assuming that you DON'T already know how prototype works:http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711?noredirect=1#comment32273530_16063711 – HMR Jan 31 '14 at 03:09

1 Answers1

0

To give each instance its own array, don't use the prototype to hold the array because it is shared among all instances. You can initialize a new array in the constructor of parent and then in the child class make sure you call the parent's constructor:

function parent(){
    this.arr = [];
}

function child() {
    parent.call(this);   // call parent constructor
}
child.prototype =  Object.create(parent.prototype);
child.prototype.constructor = child;

Now every parent object will have its own copy of the array including the ones that are part of the child descendants.

See this MDN article for a good explanation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

jfriend00
  • 683,504
  • 96
  • 985
  • 979