在obj.prototype = new ParentObj()之后消失的对象方法;在JavaScript中 [英] Object method gone after obj.prototype = new ParentObj(); in JavaScript

查看:182
本文介绍了在obj.prototype = new ParentObj()之后消失的对象方法;在JavaScript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaScript继承对象。看一下这个例子:

I am trying inherit objects in JavaScript. Take a look at this example:

var BaseObject = function() {
};

var ChildObject = function() {
};

ChildObject.prototype.childMethod = function() {
};

ChildObject.prototype = new BaseObject();
ChildObject.prototype.constructor = ChildObject();

但是,只要我做原型继承,childMethod()就会消失。我在这里做错了什么?

However, as soon as I do prototypal inheritance, the childMethod() disappears. What am I doing wrong here?

推荐答案

当你将原型分配给BaseObject并且BaseObject的原型没有childMethod方法时,你会覆盖原型。

You are overwriting the prototype when you assign it to BaseObject and BaseObject's prototype has no childMethod method.

要获得所需的行为,您必须在将原型分配给BaseObject后添加childMethod:

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());

这篇关于在obj.prototype = new ParentObj()之后消失的对象方法;在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆