Javascript - 从内部函数设置原型

时间:2015-03-02 10:06:19

标签: javascript inheritance prototype

这有效:

function Bird(name){
    Animal.call(this,name);
    this.speak = function(){
        console.log("Tweeet!");
    }
}
Bird.prototype.constructor = Animal;

这会引发"无法设置属性'构造函数'未定义"

function Bird(name){
    Animal.call(this,name);
    this.speak = function(){
        console.log("Tweeet!");
    }
    this.prototype.constructor = Animal;
}

为什么会这样?在第二个例子中,这个应该是 Bird ,因为我用 new 调用了函数,所以我应该能够设置<的原型即可。我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

Object个实例(this)没有prototype属性,因此this.prototype会返回undefined

您有两种方法可以解决这个问题:

  1. 按照您在第一个代码段中的操作调用Bird.prototype

    function Bird(name){
        Animal.call(this,name);
        this.speak = function(){
            console.log("Tweeet!");
        }
        Bird.prototype.constructor = Animal;
    }
    
  2. 使用Object.getPrototypeOf来获取对象的原型:

    function Bird(name){
        Animal.call(this,name);
        this.speak = function(){
            console.log("Tweeet!");
        }
        Object.getPrototypeOf(this).constructor = Animal;
    }
    
  3. 当您不知道对象的类型时,选项2会更有用。在您的示例中,您位于Bird类中,因此选项1更有意义。


    以下是一个有用的示例,希望您的评论中的问题更加清晰:

    &#13;
    &#13;
    // 1. Tell Javascript what an Animal is
    // This will create an Object called Animal, but it is a blueprint not an actual Animal.
    
    function Animal(name)
    {
        this.name = name;
    }
    
    // 2. Tell Javascript what a Bird is
    // This will create an Object called Bird, but it is a blueprint not an actual Bird. So it cannot speak!
    
    // or function Bird(name){
    var Bird = function(name){
        Animal.call(this,name);
        this.speak = function(){
            alert("Tweeet! said " + this.name);
        }
        
        Object.getPrototypeOf(this).constructor = Animal;
    };
    
    // 3. Now create an actual Bird which can speak 
    
    var tweety = new Bird("Tweety Pie");
    tweety.speak();
    &#13;
    &#13;
    &#13;

相关问题