我只是將其中的例子做成html檔案,便於調試罷了。 1. 建構函式綁定 [javascript] <html> <head> <script type="text/javascript"> function Animal(){ this.species = "動物"; } Animal.prototype.species2 = "動物2" function Cat(name,color){ Animal.apply(this, arguments); this.name=name; this.color=color; } Cat.prototype.type = "貓科動物"; Cat.prototype.eat = function(){alert("吃老鼠")}; var cat1 = new Cat("大毛","黃色"); var cat2 = new Cat("二毛","黑色"); alert(cat1.species); // 大毛 alert(cat1.species2); // 黃色 </script> </head> <body> Test </body> </html> 但是這種方法只適合本地變數的繼承,並且Animal和Cat之間也沒有關係。看,可以看到從cat1並不能訪問Animal.prototype.species2。 2。 prototype模式 [javascript] <html> <head> <script type="text/javascript"> function Animal(){ this.species = "動物"; } function Cat(name,color){ this.name=name; this.color=color; } Cat.prototype = new Animal(); Cat.prototype.constructor = Cat; Cat.prototype.type = "貓科動物"; Cat.prototype.eat = function(){alert("吃老鼠")}; var cat1 = new Cat("大毛","黃色"); var cat2 = new Cat("二毛","黑色"); alert(cat1.name); // 大毛 alert(cat1.color); // 黃色 </script> </head> <body> Test </body> </html> 從可以看出,prototype還是沒有改變javascript內部的繼承關係,見直角方框; 圓角方框中的內容就是通過改變prototype,來實現繼承。 3. 直接繼承prototype [javascript] <html> <head> <script type="text/javascript"> function Animal(){ } Animal.prototype.species = "動物"; function Cat(name,color){ this.name=name; this.color=color; } Cat.prototype = Animal.prototype; Cat.prototype.constructor = Cat; Cat.prototype.type = "貓科動物"; Cat.prototype.eat = function(){alert("吃老鼠")}; var cat1 = new Cat("大毛","黃色"); var cat2 = new Cat("二毛","黑色"); alert(cat1.name); // 大毛 alert(cat1.color); // 黃色 </script> </head> <body> Test </body> </html> 從下面的上可以看出,修改Cat.prototype會同時修改Animal.prototype。 4. 利用Null 物件作為中介 [javascript] <html> <head> <script type="text/javascript"> function extend(Child, Parent) { var F = function(){}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.uber = Parent.prototype; } function Animal(){ } Animal.prototype.species = "動物"; Animal.prototype.birthPlaces = ['北京','上海','香港']; function Cat(name,color){ this.name=name; this.color=color; } extend(Cat,Animal); Cat.prototype.type = "貓科動物"; Cat.prototype.eat = function(){alert("吃老鼠")}; var cat1 = new Cat("大毛","黃色"); cat1.birthPlaces.push('廈門'); var cat2 = new Cat("二毛","黑色"); alert(cat1.name); // 大毛 alert(cat1.color); // 黃色 </script> </head> <body> Test </body> </html> 但是這種方法,還是存在子類修改父類的方法。 [javascript] cat1.birthPlaces.push('廈門'); 會直接導致Animal中的birthPlaces變數變化,這時就會牽扯到淺拷貝和深拷貝了。 一句話,上面的方法,都是在類比繼承,但是都不是正的繼承。 javascript中現在還不支援繼承,只能能下一個版本。