下面是JavaScript教程中非常经典的继承方法。 复制代码 代码如下: //定义一个Pet对象。通过这一个名称和数量的腿。 var Pet = function (name,legs) { this.name = name; //Save ths name and legs values. this.legs = legs; };
//创建一个方法,显示了Pet的名字和数量的腿。 Pet.prototype.getDetails = function () { return this.name + " has " + this.legs + " legs "; }
//定义一个Cat对象,继承从Pet。 var Cat = function (name) { Pet.call(this,name,4); //调用这个父对象的构造函数 };
//这条线执行继承从Pet。 Cat.prototype = new Pet();
//增加一个动作方法的猫 Cat.prototype.action = function () { return "Catch a bird"; };
//创建一个实例petCat的猫。 var petCat = new Cat("felix");
var details = petCat.getDetails(); console.log(details) //"felix has 4 legs". var action = petCat.action(); console.log(action) //"Catch a bird". petCat.name = "sylvester"; //改变petCat的名字 petCat.legs = 7; //改变petCat腿的数量 details = petCat.getDetails(); console.log(details) //"sylvester has 7 legs".
上述方法虽然执行起来没有太大的问题,但是代码整体风格略显臃肿,并不很优雅。在外面还是可以对属性进行修改。这种方法没有对继承的属性进行保护。下面一种方法,省去的new和prototype,利用“函数继承”的特性实现。 复制代码 代码如下: //定义一个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".