我试图在子类中使用父类的方法。在其他语言中,您只需要使用 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();
最佳答案
我明白下面的代码不一定像其他 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/