1. 程式人生 > >js繼承 - 建構函式繼承,call apply改變this指向 原型鏈繼承,混合繼承

js繼承 - 建構函式繼承,call apply改變this指向 原型鏈繼承,混合繼承

1、建構函式繼承

function Person(name,age){
		this.name = name;
			this.age = age;
			this.run = function(){
				console.log('跑....');
			}
		}
		function YPerson(name,age,color){
			this.method = Person;//this.method指向Person所指向的建構函式Person
			this.method(name,age); //執行this.method方法,即執行Person所指向的函式  YPerson就繼承了Person的所有的屬性和方法
			
			this.color = color;
		}
		var res = new YPerson('小王',18,'yellow');
		res.run();  //跑....

本質是在子類中,呼叫父類建構函式,從而讓子類擁有父類的屬性和方法

2、call/apply方法

all和apply都是為了改變某個函式執行時的context即上下文而存在的,換句話說,就是為了改變函式內部this的指向。
二者作用完全一樣,只是接受引數的方式不太一樣。

call方法是Function類中的方法接受2個引數
call方法的第一個引數的值賦值給類(即方法)中出現的this
call方法的第二個引數開始依次賦值給類(即方法)所接受的引數

apply方法接受2個引數,
第一個引數與call方法的第一個引數一樣,即賦值給類(即方法)中出現的this
第二個引數為陣列型別,這個陣列中的每個元素依次賦值給類(即方法)所接受的引數

function Person(name,age){
		this.name = name;
			this.age = age;
			this.run = function(){
				console.log('跑....');
			}
		}
		function YPerson(name,age,color){
//			Person.call(this,name,age);  //call
			Person.apply(this,[name,age]);	//apply
			this.color = color;
		}
		var res = new YPerson('小王',18,'yellow');
		res.run();  //跑....
		console.log(res);

3、原型鏈繼承
物件的屬性和方法,有可能定義在自身,也有可能定義在它的原型物件。由於原型本身也是物件,又有自己的原型,所以形成了一條原型鏈

function Box() { //Box建構函式
		this.name = '小王';
		}
		function Desk() { //Desk建構函式
			this.age = 18;
		}
		Desk.prototype = new Box(); //Desc繼承了Box,通過原型,形成鏈條
		var desk = new Desk();
		console.log(desk.name);//小王  得到繼承的屬性

原型鏈繼承個原理:
將一個建構函式的原型指向另一個建構函式的例項物件來實現繼承。

4、混合繼承

function Box(age) {
		this.name = '小王';
			this.age = age;
		}
		Box.prototype.run = function() {
			return this.name + this.age;
		};
		function Desk(age) {
			this.method = Box;//this.method指向Person所指向的物件函式。
			this.method(age);//執行this.method方法,即執行Person所指向的函式  YPerson就繼承了Person的所有的屬性和方法     建構函式繼承    繼承age 屬性
		}
		Desk.prototype = new Box(); //原型鏈繼承   run方法
		var desk = new Desk(18);
		console.log(desk.run());//小王18