call(),apply(),bind()区别

JavaScript 提供了call、apply、bind这三个方法,来切换/固定this的指向。

call(),apply()的功能一模一样,只是使用方式不同

call()

thisValue就是this指向的对象,arg1,arg2等都是传入的参数。thisValue调用func下的方法

func.call(thisValue, arg1, arg2, …)

call方法的参数,必须是一个对象。如果参数为空、null和undefined,则默认传入全局对象。

var n = 123;
var obj = { n: 456 };
function a() {
console.log(this.n);
}
a.call() // 123
a.call(null) // 123
a.call(undefined) // 123
a.call(window) // 123
a.call(obj) // 456

apply()

apply()方法的用法和call()一样,唯独不同的是传入的第二个参数是数组

func.apply(thisValue, [arg1, arg2, …])

function f(x, y){
console.log(x + y);
}
f.call(null, 1, 1) // 2
f.apply(null, [1, 1]) // 2

如上,f函数本来是接收两个参数,但使用apply的话只需要传入一个数组,利用这一点可以找出数组的最大最小值:

var ob =[3,5,2,7];
Math.max.apply(null,ob); //7

还可以将数组的空元素变为undefined

var ob = [‘a’,‘b’];
Array.apply(null,ob); // 输出[‘a’,undefined,‘b’]

bind()

bind方法用于将函数体内的this绑定到某个对象,然后返回一个新函数。

var person = {
age: 0,
inc: function () {
this.age++;
}
};
var fun = person .inc.bind(person);
fun();
person .age// 1

猜你喜欢

转载自blog.csdn.net/weixin_41796860/article/details/84769524