gpt4 book ai didi

JavaScript 继承

转载 作者:IT王子 更新时间:2023-10-29 02:46:57 25 4
gpt4 key购买 nike

<分区>

我正在尝试在 javascript 中实现继承。我想出了以下最少的代码来支持它。

function Base(){
this.call = function(handler, args){
handler.call(this, args);
}
}

Base.extend = function(child, parent){
parent.apply(child);
child.base = new parent;
child.base.child = child;
}

专家,请让我知道这是否足够或我可能遗漏的任何其他重要问题。基于面临的类似问题,请提出其他更改建议。

完整的测试脚本如下:

function Base(){
this.call = function(handler, args){
handler.call(this, args);
}
this.superalert = function(){
alert('tst');
}
}

Base.extend = function(child, parent){
parent.apply(child);
child.base = new parent;
child.base.child = child;
}

function Child(){
Base.extend(this, Base);
this.width = 20;
this.height = 15;
this.a = ['s',''];
this.alert = function(){
alert(this.a.length);
alert(this.height);
}
}

function Child1(){
Base.extend(this, Child);
this.depth = 'depth';
this.height = 'h';
this.alert = function(){
alert(this.height); // display current object height
alert(this.a.length); // display parents array length
this.call(this.base.alert);
// explicit call to parent alert with current objects value
this.call(this.base.superalert);
// explicit call to grandparent, parent does not have method
this.base.alert(); // call parent without overriding values
}
}

var v = new Child1();
v.alert();
alert(v.height);
alert(v.depth);

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