Javascript 原型(prototype) - 多个成员函数

标签 javascript prototype

我有一个 javascript 对象 PathDiagramElement,它的原型(prototype)成员很少。有一个 PassiveElement 对象,它的原型(prototype)是 PathDiagramElement。

也是PassiveElement,有很多自己的原型(prototype)成员。

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() 工作正常。但是 p.getTest() throws undefined is not a function error.

但如果我改变

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

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

一切正常。

如何定义一个对象,它有多个自己的原型(prototype)成员并且必须使用另一个对象的原型(prototype)?

提前致谢。

最佳答案

你真的只需要两者的结合。在第一种情况下,您将用一个全新的对象覆盖 PassiveElementprototype。相反,您需要创建一个新的 PathDiagramElement,然后为该相同 对象的新属性赋值,就像您在第二个示例中所做的那样。像这样:

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

真的没有办法解决这个问题。有扩展现有对象的便捷方法,但归根结底,您需要的是为现有对象的新属性赋值。

注意以下是等价的:

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

关于Javascript 原型(prototype) - 多个成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24375615/

相关文章:

javascript - 在 Javascript 中访问私有(private)成员的更好方法

javascript - 如何正确触发onClick事件

javascript - 了解 JavaScript 原型(prototype)

javascript - 方法在现代浏览器中返回 __proto__ ?如何去除它?

javascript - 如何在 Firefox 3.x 中覆盖 addEventListener?

javascript - 使用原型(prototype)时如何引用父对象?

javascript - 在 LocalStorage 上保存身份验证数据 react js

javascript - 处理由另一个函数调用的异步函数时出现的问题

javascript - 母版页 js/代码在子文件夹中不起作用

javascript - 使 javascript 数组中的值之间的距离彼此相等