javascript類與繼承

    "父類"
    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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章