簡體   English   中英

javascript中繼承的正確語法

[英]Correct syntax for inheritance in javascript

非常瑣碎的問題

我試圖了解javascript中的繼承

function Animal() {
  this.eats = true;
}
function Rabbit() {
  this.jumps = true;
}
//Rabbit is-a Animal
Rabbit.prototype = Animal;  //I'm assuming this does not inherit

alert(Rabbit.prototype.eats); // returns undefined

正確的方法是什么?

這是“有答案的”,但請允許我為后代提供替代方法。

調用父級的構造函數以獲取父級的原型不是一個好主意。 這樣做可能會有副作用; 設置ID,跟蹤實例數,無論構造函數內部發生什么情況。

您可以在Child構造函數中使用Parent.call(),然后在Object.create或polyfill中使用其原型:

function Animal () {
    this.eats = true;
}

function Rabbit (legs) {
    Animal.call(this);
    this.jumps = true;
}
Rabbit.prototype = Object.create(Animal.prototype);

// Or if you're not working with ES5 (this function not optimized for re-use):
Rabbit.prototype = (function () {
                        function F () {};
                        F.prototype = Animal.prototype;
                        return new F();
                    }());

var bugs = new Rabbit();
alert(bugs instanceof Animal); // true
alert(bugs.eats); // true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM