user3377206
user3377206

Reputation: 135

Javascript Prototype - Multiple member functions

I have a javascript object PathDiagramElement that has few prototype members. There is a PassiveElement object whose prototype is PathDiagramElement.

Also PassiveElement, has a lot of prototype members of its own.

var PathDiagramElement = function(){};

PathDiagramElement.prototype =  {    
    myself : "Parent",
    getTest :  function() {
        return this.myself + " function";
    }
};
var PassiveElement = function() {};
PassiveElement.prototype = new PathDiagramElement();
PassiveElement.prototype = {
         myself : "Child",
         getTestChild : function() {
                return this.myself+ " function";
    }
};

var p = new PassiveElement();
alert(p.getTestChild());
alert(p.getTest());

p.getTestChild() works fine. But p.getTest() throws undefined is not a function error.

But if I change

PassiveElement.prototype = {
         myself : "Child",
         getTestChild : function() {
                return this.myself+ " function";
    }
};

to

PassiveElement.prototype.myself = "Child";
PassiveElement.prototype.getTestChild = function() {
                return this.myself+ " function";
    }

everything works fine.

How do I define an object that has multiple prototype members of its own as well as has to use a prototype of another object?

Thanks in advance.

Upvotes: 1

Views: 454

Answers (1)

Wayne
Wayne

Reputation: 60414

You really just need a combination of the two. In the first case, you're overwriting the prototype of PassiveElement with an entirely new object. Instead, you need to create a new PathDiagramElement and then assign values to new properties on that same object, as you do in the second example. Like this:

PassiveElement.prototype = new PathDiagramElement();
PassiveElement.prototype.myself = "Child";
PassiveElement.prototype.getTestChild = function() {
    return this.myself + " function";
}

There's really no way around this. There are convenience methods for extending existing objects, but, at the end of the day, what you need is to assign values to new properties of an existing object.

Note that the following is equivalent:

var pathDiagramEl = new PathDiagramElement();
pathDiagramEl.myself = "Child";
pathDiagramEl.getTestChild = function() {
    return this.myself + " function";
}
PassiveElement.prototype = pathDiagramEl;

Upvotes: 4

Related Questions