js類的繼承與創建

類的創建和繼承

類的創建,new 一個function ,在這個function的prototype裏面增加屬性和方法。

function A(food){

}

A.prototype.eat=function(food){
}

原型繼承:

Student.prototype=new Person();
Student.prototype.constructor=Student;

缺點:無法設置構造函數的參數
借用構造函數繼承:

function fn(x,y){
console.log(this);
console.log(x+y);
}

var o={
name:'zs'
};
//bind方法 改變函數的this 並且返回一個新的函數 不調用函數
var f=fn.bind(o,1,2);
f();
//call函數 改變函數中的this 直接調用函數
fn.call(o.2.3);
		function Person(name,age,sex){
			this.name=name;
			this.age=age;
			this.sex=sex;
			
		}
		
		function Student(name,age,sex,score){
			Person.call(this,name,age,sex);//改變person的this 使其變成student 
			this.score=score;
			
		}
		
		var s1=new Student('zs',13,'男',100);
		console.dir(s1);

缺點:只可繼承屬性,不能繼承方法。

組合繼承:
繼承方法與屬性綜合:
綜合call方法和

Student.prototype=Person.prototype;
Student.prototype.constructor=Student;

但只有一個對象指向,即student增加一個方法,person也增加一個同樣的方法。若想子類型只有某個方法而父類型沒有,則結合以下:

Student.prototype=new Person();
Student.prototype.constructor=Student;
發佈了142 篇原創文章 · 獲贊 42 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章