JavaScript:使用子类的父方法?

标签 javascript polymorphism superclass subclassing

我试图在子类中使用父类的方法。在其他语言中,您只需要使用 extends 并且父项中的所有方法都可以在子项中使用,但在 JavaScript 中,这似乎有所不同。

function Svg() {
    this.align = function(value) {
        if(value === 'left') return 0;
    }
}

function Graph() {
    // I want to align text to the left
    console.log('<text x="' + align('left') + '"></text>');
}

graph = new Graph();
Graph.prototype = new Svg();
Graph.prototype.align.call();

http://jsfiddle.net/cBMQg/9/

最佳答案

我明白下面的代码不一定像其他 OOP 语言那样“扩展”。但它确实将另一个函数/类作为属性 - 您可以直接调用它的方法。此外,我没有为这个演示使用 JavaScript 原型(prototype)。

<script>
    function Svg() {
        this.align = function( align ) {
            if( align == 'left') 
                return 'left';
            else
                return 0;
        }
    }

    function Graph() {

        this.Svg = new Svg();
        // I want to align text to the left
        this.AlignLeft = function( direction ) {
            console.log('<text x="' + this.Svg.align( direction ) + '"></text>');
        }
    }

    graph = new Graph();
    graph.AlignLeft('left');  //console.log <text x="left"></text> 
</script>

fiddle :http://jsfiddle.net/cBMQg/11/

关于JavaScript:使用子类的父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19213586/

相关文章:

javascript - 如何使用 FRP(和 bacon.js)防止事件循环

用于隐藏类型特定实现的 Java 泛型?

c++ - 我可以在 C++ 抽象类中添加什么类型的成员

c++ - 构造函数调用子类

java - 为什么在 put 方法中使用泛型声明 "<? super ArrayList> does not accept value "new Object()"的 HashMap?

javascript - 使用 Redux 而不使用 npm

javascript - JSON.stringify 和数字作为字符串

arrays - 如何构建对象层次结构,使所有名词都是单词但并非所有单词都是名词

Javascript:让对象继承数组方法

c++ - 我可以调用从 main() 重写的虚拟函数吗?