0

For the following code...

function ClassA() {
    this.name = "ClassA";
    this.sayParentName = function () {
        console.log(this.name);
    };
};

function ClassB() {
    this.name = "ClassB";
    sayName = function () {
        console.log(this.name);
    };
};
ClassB.prototype = new ClassA();

var test1 = new ClassB();
var test2 = new ClassB();
test1.sayParentName();
test2.sayParentName();

is there only one instance of sayParentName from the parent ClassA in memory? Or is a new instance in memory created for each new object of ClassB created (each ClassB has its own sayParentName function that it's inherited instead of just using a single sayParentName from the parent class)

If there is a new instance created is the only way around this to set the prototype of ClassA to be a function (sayParentName) for example after creating the ClassA object

ClassA.prototype.sayParentName = function() { console.log( this.name) );
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Ben Cheng
  • 101
  • 3
  • 9
  • 1
    See what `test1.sayParentName === test2.sayParentName` tells you. FYI, creating a new instance of the parent class is not a good way to set up inheritance. Have a look at http://stackoverflow.com/q/17392857/218196 for a better alternative. – Felix Kling Dec 08 '13 at 07:18
  • Thanks, turns out they are pointing to the same instance. As for the link, I would have to play around with object.create, but I don't see the advantage of new vs object.create when we would actually need to use the "Animal" constructor with a parameter, or properties of the parent "Animal" class. I can see the advantage or sense it would make to use object.create if we just needed methods from the animal prototype (or animal itself it thats possible). Thanks for your help! – Ben Cheng Dec 08 '13 at 08:10

0 Answers0