function People(hobby) {
this.name="mike";
this.age=12;
this.hobby=hobby;
this.fun=function (){
}
}
var obj={};
var obj2={};
function Sun (){
People.call(this,"swim");
People.call(obj,"running");//call方法传递实参直接写
People.apply(obj2,["hiking"]) //apply方法传递实参需要用arguments
}
var a=new Sun ()//实例化Sun
console.log(a);// {name: "mike", age: 12, hobby: "swim", fun: ƒ}
console.log(obj);//{name: "mike", age: 12, hobby: "running", fun: ƒ}
console.log(obj2);//{name: "mike", age: 12, hobby: "hiking", fun: ƒ}
总结:
当在函数内部使用call调用People函数时,People函数原来的this指向People函数里的狭义对象,而在Sun中使用call方法时,this指向当前Sun狭义对象,相当于对原来的this重新赋值,this=this(Sun) 如果调用People不传实参,则相当于直接调用People函数,此时Sun函数中name,age属性和一个方法,如果传入实参,则Sun函数里有三个属性一个方法。
apply方法传递实参需要用arguments,用法和call方法相同
call方法和apply第一个参数改变原函数this指向,第二个函数为调用函数时传入的实参(传参方式不同),this可以指向任何对象。