在学习call和apply时我们知道他们的作用是改变this指向,区别是传参形式不同。
1.call
function Person(name,age){
//this==obj
this.name=name,
this.age=age
}
var person =new Person('haha',18);
var obj ={};
Person.call(obj,'hehe',19);
console.log(obj)
//{name: "hehe", age: 19}
我们可以看见第一个参数可以改变this的指向,而第一个参数之后就是对应函数的形参,且函数会默认调用
2.apply
Person.apply(obj,['haha',18]);
console.log(obj)
//{name: "haha", age: 19}
apply会有两个参数 第一个改变this指向,第二个是数组,内容同样对应函数的形参,且函数会默认调用
3.bind
Person.bind(obj,'xixi',20)();
console.log(obj)
//{name: "xixi", age: 20}
bind与call用法基本相同,区别在于bind函数不会默认调用。