JavaScript继承

JavaScript继承

我试图在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);


茅侃侃
浏览 379回答 3
3回答

白衣非少年

当我玩JS对象时,我找到了一个更简约的解决方案:-)享受!function extend(b,a,t,p) { b.prototype = a; a.apply(t,p); }例function A() {    this.info1 = function() {        alert("A");    }}function B(p1,p2) {    extend(B,A,this);    this.info2 = function() {        alert("B"+p1+p2);    }}function C(p) {    extend(C,B,this,["1","2"]);    this.info3 = function() {        alert("C"+p);    }}var c = new C("c");c.info1(); // Ac.info2(); // B12c.info3(); // Cc
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript