为什么不通过原型链继承对象?

时间:2015-09-25 11:05:21

标签: javascript inheritance methods

我对Javascript很新,并且在理解原型链时遇到一些麻烦。我的理解是,如果你创建一个对象(“cat”),并将该对象的原型设置为另一个对象(“animal”),你将继承它的属性和方法。

然而,在我的沙盒程序中,我没有看到这种情况发生。我认为我对原型继承的理解肯定有问题。

(function() {

    window.onload = function() {
        document.getElementById("main").innerHTML = getMessage();
    }

    function animal(){
        this.speak = function(){
            return "I am a " + this.species + ", hear me " + this.sound;
        }
    }

    function getMessage(){
        var cat = {};
        cat.prototype = new animal();
        cat.species = "cat";
        cat.sound = "meow";
        return cat.speak();    //Causing error: cat.speak() not defined
    }

})()

我认为如果你设置一个对象的原型并尝试访问一个不存在的方法或属性,JS会自动上去寻找该方法的原型链。但我不认为这里发生了这种情况,我不明白为什么。

我注意到我这样做时效果很好:

var cat = Object(new animal());

我很高兴这样做,但我想了解为什么第一种方法不起作用。

非常感谢你的时间。

1 个答案:

答案 0 :(得分:1)

您将.prototype.__proto__混淆。

以下作品:

(function() {

    window.onload = function() {
        document.getElementById("main").innerHTML = getMessage();
    }

    function animal(){
        this.speak = function(){
            return "I am a " + this.species + ", hear me " + this.sound;
        }
    }

    function getMessage(){
        var cat = {};
        cat.__proto__ = new animal();
        cat.species = "cat";
        cat.sound = "meow";
        return cat.speak();    //Causing error: cat.speak() not defined
    }

})()

另见__proto__ VS. prototype in JavaScript

相关问题