0
Q
無法從父
A
回答
3
看起來你想讓父構造函數自動調用,沒有一些額外的工作就不支持。您的代碼應該看起來像下面這樣:
function Alive(name) {
this.name = name;
}
function Cat(name) {
// Call the parent constructor
Alive.call(this, name);
}
Cat.prototype = new Alive();
// This line is to fix the constructor which was
// erroneously set to Alive in the line above
Cat.prototype.constructor = Cat;
var cat = new Cat('Thomas');
alert(cat.name);
如果您使用庫來實現繼承,則不必擔心這一點。如果你不想創建一個空構造函數,它們甚至可以自動調用你的父構造函數。上面的代碼仍然不理想。看看我寫的一篇文章,談論的是「正確的」繼承方式。 http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html
0
因爲貓不接受論據。這是你想要的:
function Alive(name) {
this.name = name;
}
function Cat(name) {
Alive.call(this, name);
}
// since there's nothing on the prototype, this isn't necessary.
// Cat.prototype = new Alive();
var cat = new Cat('Tomas');
alert(cat.name);
相關問題
- 1. 無法從iframe訪問父元素
- 2. 無法從iframe調用父函數
- 3. 無法獲取父窗口從自身
- 4. 無法從父活動接收意向?
- 5. 無法從片段獲取父視圖
- 6. jquery - 無法隱藏父div
- 7. 無法刪除父項
- 8. Qt的 - 無法父控件
- 9. 無法實例類型父
- 10. jQuery - 無法隱藏父項
- 11. 無法移除父div
- 12. 無法摧毀父對象
- 13. 無法從子UI訪問父控制器的方法
- 14. DataMapper Redis:無法從父項中找到子項,只有子項的父項
- 15. 從父方法調用重寫的父方法
- 16. 從孩子::方法調用父::方法
- 17. codeigniter從父方法獲取方法名
- 18. 無法使用selenium webdriver從彈出框切換回父窗口
- 19. 子包無法從父ssis包讀取參數值
- 20. 無法從非父VC更新嵌入式子VC VC
- 21. 嵌套的ListView無法從父列表視圖獲取值
- 22. Maven2無法從相對路徑中找到父項
- 23. 無法捕獲從iframe父窗口中發生的錯誤
- 24. 無法從閉包訪問父字符串?
- 25. 無法從父組件獲取子元素
- 26. 無法從遠程IFrame調用父函數
- 27. 從父類靜態var無法正常工作
- 28. Swift 2,SpriteKit,我無法從父項中刪除一個節點
- 29. 子UITableViewController無法從父UITableViewController接收通知?
- 30. 無法從子視圖訪問父模型
這個例子沒有設置原型鏈,所以它不是繼承。 –
正如代碼註釋中所提到的,沒有理由將其設置爲無需繼承。如果在原型上定義了任何東西,那就會有所不同。 – Jeremy
設置原型鏈仍然需要,否則'cat instanceof Alive'將返回false –