[英]JavaScript: Use parent methods from child class?
我正在尝试使用子类中父类的方法。 在其他语言中,您只需要使用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原型来进行此演示。
<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>
小提琴 : http : //jsfiddle.net/cBMQg/11/
function Svg() {
this.align = function(value) {
if(value === 'left') return 0;
}
}
function Graph() {
Svg.call(this); // Call the Super Class Constructor with changed THIS
// I want to align text to the left
console.log('<text x="' + align('left') + '"></text>');
}
graph = new Graph();
Graph.prototype = new Svg();
graph.align('left');
答案可能有效,但为什么没有原型使用? 对齐函数是否会在每个实例上执行不同的逻辑?
正如Bergi指出的那样; JavaScript使用原型继承,最好在原型上定义不在实例之间更改的成员:
简单解释; prototype可用于声明不会为实例更改的成员/属性。 如果我声明一个名为Person的对象,而person有2个成员:name和greet。 Greet将输出“Hello,我是[this.name]”,因此greet不会在实例之间发生变化。
当我在Person原型上声明greet方法然后创建数千个Person实例(ben,jack,mary ....)时,它们将只共享一个greet
函数。 这节省了对象初始化的内存和CPU时间。 有关详细信息,请查看此链接: https : //stackoverflow.com/a/16063711/1641941
通过下面的链接可以帮助你了解this
是指在JavaScript中。 https://stackoverflow.com/a/19068438/1641941
function Svg() {
this.someInstanceValue=22;
}
Svg.prototype.align = function(value) {
if(value === 'left') return 0;
}
function Graph() {
// get Svg's instance properties
Svg.apply(this,arguments);
console.log('<text x="' + this.align('left') + '"></text>');
}
//inherit from Svg:
Graph.prototype=Object.create(Svg.prototype);
Graph.prototype.constructor=Graph;
graph = new Graph();
graph.align('left');
如果您不想从Svg继承而是将其混合在一起,那么您仍然可以使用原型来混合它的函数(并调用Svg.apply来获取所需的实例成员):
function mixin(source, target){
for(thing in source){
if(source.hasOwnProperty(thing)){
target[thing]=source[thing];
}
}
};
function Svg() {
this.someInstanceValue=22;
}
Svg.prototype.align = function(value) {
if(value === 'left') return 0;
}
function Graph() {
// get Svg's instance properties
Svg.apply(this,arguments);
console.log('<text x="' + this.align('left') + '"></text>');
}
//mix in Svg:
mixin(Svg.prototype, Graph.prototype)
graph = new Graph();
graph.align('left');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.