blog
blog copied to clipboard
JavaScript中函数的call和apply以及bind
上一篇介理清了this在不同场景中的指向,这一篇继续讲一下有关的内容。
在Function对象中,都有call,apply,bind三个方法,他们可以将一个对象绑定到这个函数中的this。
var c = 1;
var obj = {
c: 2,
}
function sum (a, b) {
console.log(this);
console.log(this.c + a + b);
}
sum(5, 6); // window, 12
sum.call(obj, 5, 6); // { c: 2 }, 13
sum.apply(obj, [5, 6]); // { c: 2 }, 13
var f = sum.bind(obj); // ƒ sum
f(5, 6) // { c: 2 }, 13