2015-09-25 86 views
0

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

我很樂意這樣做,但我想明白爲什麼第一種方法是行不通的。

非常感謝您的時間。

回答

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

+0

謝謝!我很感激爲我清理。 – SemperCallide