一幅图看懂prototype与[[Prototype]]

首先明确:函数

一、任何对象都有属性[[Prototype]];this

二、只有函数有属性prototype。spa

 

Pet为父类,子类Dog继承Pet。示意图以下:prototype

 

继承的样例代码:code

    // 父类构造函数
    function Pet(name,sound){
        var name = name;
        this.sound = "Pet says " + sound;
        this.getName = function(){
            console.log(name);
        };
    }
    // 父类原型
    Pet.prototype.voice = function(){
        console.log(this.sound);
    }

    // 子类
    function Dog(sound){            
        this.sound = "Dog syas " + sound;
    }

    // 继承
    Dog.prototype = new Pet("pet","ohooo");
    Dog.prototype.constructor = Dog;

    // 继承验证
    var dog = new Dog("wangwang");
    dog.voice();//Dog syas wangwang
    dog.getName();//pet

 

Firefox中的显示以下:

相关文章
相关标签/搜索