原型,原型链,call/apply(5)-实战,call和apply的区别

 

实战:

function Person (name,age,sex){
				this.name =name;
				this.age = age;
				this.sex = sex;
			}
			function Student(name,age,sex,tel,grade){
				this.name =name;
				this.age = age;
				this.sex = sex;
				this.tel = tel;
				this.grade = grade;
			}
	var student = new Student("sunny",123,"male",139,2017)

改:

function Person (name,age,sex){
				this.name =name;
				this.age = age;
				this.sex = sex;
			}
			function Student(name,age,sex,tel,grade){
				Person.call(this,name,age,sex)
				this.tel = tel;
				this.grade = grade;
			}
			var student = new Student("sunny",123,"male",139,2017)

Call借用别人的函数实现自己的功能。存在于你的功能全部涵盖于别人身上。

function Wheel(wheelSize,style){
				this.style = style;
				this.wheelSize = wheelSize;
			}
			function Sit(c,sitColor){
				this.c = c;
				this.sitColor = sitColor;
			}
			function Model(height,width,len){
				this.height = height;
				this.width = width;
				this.len = len;
			}
			function Car(wheelSize,style,c,sitColor,height,width,len){
				Wheel.call(this,wheelSize,style);
				Sit.call(this,c,sitColor);
				Model.call(this,height,width,len);
			}
			var car = new Car(100,"hua","真皮","red",1800,1900);

call和apply的区别:

传产列表:第一位传的都是改变this指向的那个,第二位call可以一位一位的传实参列表进去,但是,apply只能传一位,而且必须是数组形式的实参。

call需要把实参按照形参的个数传进去,

apply需要传一个arguments

function Car(wheelSize,style,c,sitColor,height,width,len){
				Wheel.apply(this,[wheelSize,style]);
				Sit.apply(this,[c,sitColor]);
				Model.apply(this,[height,width,len]);
			}

猜你喜欢

转载自blog.csdn.net/hdq1745/article/details/82188987