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

猜你喜欢

转载自blog.csdn.net/D321xiaoding/article/details/83245573