JavaScript的出現已經將近20多年了,但是對這個預言的褒貶還是眾說紛紜。很多人都說JavaScript不能算是面向對象的變成語言。但是JavaScript的類型非常松散,也沒有編譯器。這樣一來給了程序員很大的自由,也帶來了一些缺陷。
雖然JavaScript不算是一門面向對象的語言。但是我們可以模仿著其他語言實現面向對象的方式來實現JavaScript的面向編程。
下面是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".
復制代碼 代碼如下:
//定義一個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".
新聞熱點
疑難解答
圖片精選