参考自:https://www.cnblogs.com/Shd-Study/archive/2017/03/16/6560808.html
1.传入参数不同
function Person(age) {
this.age = age;
}
Person.prototype.sayHi = function (x, y) {
console.log((x + y) + ":====>" + this.age);//是实例对象
};
function Student(age) {
this.age = age;
}
var per = new Person(10);//实例对象
var stu = new Student(100);//实例对象
//sayHi方法是per实例对象的
per.sayHi.apply(stu, [10, 20]);
per.sayHi.call(stu, 10, 20);
console.log(per.sayHi.apply(stu, [10, 20]));//输出 30:====>100
apply的使用语法
函数.apply(对象,[参数1,参数2,...]);
call的使用语法(bind与call传入参数形式相同)
函数.call(对象,参数1,参数2,...);
作用:改变this的指向
不同的地方:参数传递的方式是不一样的
只要是想使用别的对象的方法,并且希望这个方法是当前对象的,那么就可以使用apply或者是call的方法改变this的指向
2.bind使用的不同
这里换成bind调用
function Person(age) {
this.age = age;
}
Person.prototype.sayHi = function (x, y) {
console.log((x + y) + ":====>" + this.age);//是实例对象
};
function Student(age) {
this.age = age;
}
var per = new Person(10);//实例对象
var stu = new Student(100);//实例对象
//sayHi方法是per实例对象的
var f1 = per.sayHi.bind(stu, 10, 20);
console.log(f1);
/*输出
ƒ (x, y) {
console.log((x + y) + ":====>" + this.age);//是实例对象
}
*/
console.log(f1()); //输出 30:====>100
由此得出结论,bind 返回的是一个新的函数,这个新函数怪变了原来函数的执行环境,但你必须调用它才会被执行。
3.bind与函数连用
function Person(name) {
this.name = name;
}
Person.prototype.eat = function () {
setInterval(function () {
console.log(this.name+"5秒吃一个包子");
}.bind(this),5000);
};
var per = new Person("jack");
per.eat();
上面代码等同于如下
function Person(name) {
this.name = name;
}
function fn1() {
console.log(this.name+"5秒吃一个包子");
}
var fn2 = fn1.bind(this);
Person.prototype.eat = function () {
setInterval(fn2,5000);
};
var per = new Person("jack");
per.eat();
setInterval原来是由window调用,原来内部的this为window。
fn1.bind(this)改变了fn1中this指向,并返回了一个新函数,这个函数赋值给f2,然后在setInterval中调用f2