Object method gone after obj.prototype = new ParentObj(); in JavaScript
I am trying inherit objects in JavaScript. Take a look at this example:
var BaseObject = function() {
};
var ChildObject = function开发者_StackOverflow() {
};
ChildObject.prototype.childMethod = function() {
};
ChildObject.prototype = new BaseObject();
ChildObject.prototype.constructor = ChildObject();
However, as soon as I do prototypal inheritance, the childMethod() disappears. What am I doing wrong here?
You are overwriting the prototype when you assign it to BaseObject and BaseObject's prototype has no childMethod method.
To get the desired behavior you have to add childMethod after assigning the prototype to BaseObject:
var BaseObject = function() {
};
var ChildObject = function() {
};
ChildObject.prototype = new BaseObject();
ChildObject.prototype.constructor = ChildObject;
ChildObject.prototype.childMethod = function() {
return 'childMethod';
};
c = new ChildObject();
alert(c.childMethod());
Basically when you set create ChildObject
var ChildObject = function() {
};
ChildObject.prototype
is pointing to a instance of Object, so when you add childMethod to prototype of ChildObject this method is added to that object.
But in this 2 lines you are replacing ChildObject prototype with new instance of BaseObject which does not know anything about childMethod
ChildObject.prototype = new BaseObject();
ChildObject.prototype.constructor = ChildObject();
Also I believe it should be
ChildObject.prototype.constructor = ChildObject;
So it creates circular reference.
精彩评论