//定义一个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".