在實際的項目中,我們通常都是用構造函數來創建一個對象,再將一些常用的方法添加到其原型對象上。最后要么直接實例化該對象,要么將它作為父類,再申明一個對象,繼承該父類。
而在繼承的時候有兩種常用方式,今天我們就來稍作探討
復制代碼 代碼如下:
//父類
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也指向Person
Student.prototype.constructor = Student; // 將Student.prototype.constructor 指回Person
看下面:
復制代碼 代碼如下:
Student.prototype.add=function(){alert("add")};
Person.prototype.add();//彈出add
2,繼承實例:
復制代碼 代碼如下:
Student.prototype = new Person(); //如果此處不傳遞參數,可以不寫();即直接寫成 new Person;
2 Student.prototype.constructor = Student;
3,利用控對象來組合1和2的優點,去掉缺點
復制代碼 代碼如下:
var F = function(){};
F.prototype = Person.prototype;
Student.prototype = new F();
Student.prototype.constructor = Student;
新聞熱點
疑難解答
圖片精選