I’ve been looking into doing inheritance in JavaScript the correct prototypal way, according to Douglas Crockford: http://javascript.crockford.com/prototypal.html
He writes: “So instead of creating classes, you make prototype objects, and then use the object function to make new instances”
I figured this was the way to do it:
var objA = {
func_a : function() {
alert('A');
}
};
var objB = Object.create(objA);
objB.func_a = function() {
alert('B');
}
objB.func_b = function() {
};
var objA_instance1 = Object.create(objA);
var objA_instance2 = Object.create(objA);
var objB_instance1 = Object.create(objB);
var objB_instance2 = Object.create(objB);
etc...
But wouldn’t this mean that there are now four instances of func_a (since it’s isn’t part of objA.prototype, it’s just “inside” it), or am I not understanding this correctly?
Also, is there any way I can reach the overridden function of a function (for example call objA.func_a inside objB.func_a)?
Thanks in advance.
You’re confusing the
prototypeproperty of constructor functions with the internal [[Prototype]] property of objects, which is inaccessible (FF makes it available as__proto__); usingObject.create()sets this internal property to its argument, soobjAandobjBwill be the actual prototypes of your ‘instance’ objects, ie no function objects will be duplicated.To call the overridden functions, access them via eg
objA.func_aand use call() or apply() to use them on the specific instances, eg