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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s