Prototypal inheritence - the correct way
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 obj开发者_开发知识库A_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.
There is only one instance of func_a
, and it is defined on objA
, that is because the Crockford's Object.create
method uses that object (objA
) simply as the prototype of your new objects:
console.log(objA_instance1.func_a == objA .func_a); // true
console.log(objA_instance2.func_a == objA .func_a); // true
func_a
on your objA_instances are reached by the prototype chain, that objects don't really own that property:
console.log(objA_instance1.hasOwnProperty('func_a')); // false
console.log(objA_instance2.hasOwnProperty('func_a')); // false
You're confusing the prototype
property of constructor functions with the internal [[Prototype]] property of objects, which is inaccessible (FF makes it available as __proto__
); using Object.create()
sets this internal property to its argument, so objA
and objB
will 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_a
and use call() or apply() to use them on the specific instances, eg
objB.func_a = function() {
objA.func_a.call(this); // call overridden method with current `this`
};
精彩评论