//定義一個pet對象。通過這一個名稱和數量的腿。 var pet = function (name,legs) { //創建一個對象that,其中名字是可以改的,但是腿數不可以改,實現了變量私有化。 var that = { name : name, getDetails : function () { return that.name + " has " + legs + " legs "; } };
return that; }
//定義一個cat對象,繼承從pet。 var cat = function (name) { var that = pet(name,4); //從pet中繼承屬性
//cat中增加一個action的方法。 that.action = function () { return "Catch a bird"; }
return that;
}
//創建一個petCat2; var petCat2 = cat("Felix");
var details = petCat2.getDetails(); console.log(details) //"felix has 4 legs". var action = petCat2.action(); console.log(action) //"Catch a bird". petCat2.name = "sylvester"; //我們可以改變名字。 petCat2.legs = 7; //但是不可以改變腿的數量 details = petCat2.getDetails(); console.log(details) //"sylvester has 4 legs".