javascript你可能不知道的4

javascrip中可以用function来定义一个类

function Base(){
    this.foo=function(){
        return ‘base’;
    }

}

那怎么实现类的继承呢?

function Derive1(){
    this.foo=function(){
        return ‘derive’;
    }

}

Derive1.prototype=new Base();

var obj1=new Derive1();

alert(obj1.foo());

还有另外一种方法:

function Derive2(){
    this.parent=Base;
    this.parent();
    this.bar=function(){
        return ‘bar’;
        }

}

var obj2=new Derive2;

alert(obj2.foo());
用这种方法还能实现多继承。
function Base2(){
    this.bar=function(){
        return ‘base2’;
    }
}
function Derive3(){
    this.base1=Base;
    this.base1();
    this.base2=Base2;
    this.Base2();
}
var obj3=new Derive3;
alert(obj3.foo());
alert(obj3.bar());

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.