javascript类与继承

来源:互联网 发布:unix网络编程 目录 编辑:程序博客网 时间:2024/04/28 16:44
    "父类"    function Foo(name){        this.name = name;    }    Foo.prototype.myName = function(){        return this.name;    };    //让Bar继承Foo    function Bar(name, label){        Foo.call(this, name);//如果需要"父类"的变量        this.label = label;    }    //"你不知道的javascript"一书中建议的继承方法,    //这样Bar.prototype._proto_=Foo.prototype    //书中说虽然Bar.prototype=new Foo()也可以,但是会有副作用    //所以在Bar里面会有一句Foo.call(this, name);    //之前在另外一书中看到的方法是Bar.prototype=new Foo(name)    //那这样会一并将name关联到Bar.prototype    Bar.prototype = Object.create(Foo.prototype);    //自己的方法    Bar.prototype.myLabel = function () {        return this.label;    };    var bar = new Bar("a", "b");    //bar既是Bar又是Foo    //a instanceof A :在a整条原型链上是否有指向A.prototype的对象    console.log(bar instanceof Bar);//true    console.log(bar instanceof Foo);//true    console.log(bar.myLabel());//b    console.log(bar.myName());//a

0 0