在實際的專案中,我們通常都是用建構函式來建立一個對象,再將一些常用的方法加入到其原型物件上。最後要麼直接實例化該對象,要麼將它作為父類,再申明一個對象,繼承該父類。 而在繼承的時候有兩種常用方式,今天我們就來稍作探討 複製程式碼 程式碼如下: //父類 function Person(name){ this.name = name;}; // 子類別 function Student(sex){ Person.apply(this,arguments); //繼承父類別的建構子 this.sex=sex; }; 1,繼承Prototype: 複製程式碼 程式碼如下: Student.prototype = Person.prototype; //執行完此句時,Student.prototype.constructor 指向的是Person,為什麼了?因為Person.prototype.constructor指向Person,物件的賦值實質上是引用賦值,所以Student.prototype.constructor也指向PersonStudent.prototype.constructor = Student; // 將Student.prototype.constructor 指回Person 用Person的原型物件來覆蓋Student的原型物件;前面說到物件的賦值實質上是引用賦值,所以如果Student.prototype上的任何修改都會體現到Person.prototype中,即子類別會影響父類別。 看下面: 複製程式碼 程式碼如下: Student.prototype.add=function(){alert(unction(){alert( "add")};Person.prototype.add();//彈出add 2,繼承實例: 複製程式碼 程式碼如下: 2 Student.prototype.constructor = Student; 用Person的實例來覆蓋Student的原型物件;創建了實例,比起前面那種,顯示是浪費內存了,不過這同時也解決了上面那種方法的缺點,即此時Student.prototype上的任何修改不會體現到Person.prototype中,即子類別不會影響父類別。 3,利用控對象組合1和2的優點,去掉缺點 複製程式碼 程式碼如下: var F = function(){}; F.prototype = Person.prototype;Student.prototype = new F();Student.prototype.constructor = Student;F是個空對象,只有上面一些原型方法,實例化時記憶體佔用較少,同時也隔離開了子類別對父類別的影響。