gpt4 book ai didi

JavaScript:使用子类的父方法?

转载 作者:行者123 更新时间:2023-11-30 12:55:45 25 4
gpt4 key购买 nike

我试图在子类中使用父类的方法。在其他语言中,您只需要使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com