【问题标题】:Why isn't object inheriting method via the prototype chain?为什么不是通过原型链继承对象的方法?
【发布时间】:2015-12-23 04:53:21
【问题描述】:

我对 Javascript 非常陌生,在理解原型链时遇到了一些麻烦。我的理解是,如果你创建一个对象(“猫”),并将该对象的原型设置为另一个对象(“动物”),您将继承它的属性和方法。

但是在我的沙盒程序中,我没有看到这种情况发生。我想我对原型继承的理解一定有问题。

(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());

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

非常感谢您的宝贵时间。

【问题讨论】:

    标签: javascript inheritance methods


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-09
      • 2017-07-06
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      相关资源
      最近更新 更多