相同
- 以傳入的第一個參數作為
this
的指向 - 都可傳入其他參數
不同
-
apply
是通過數組來傳遞 -
call
是按參數列表傳遞
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2])
-
bind()
方法會創建一個新函數,稱為綁定函數
var obj = {
x: 1,
};
var foo = {
getX: function() {
return this.x;
}
}
console.log(foo.getX.bind(obj)()); //1
console.log(foo.getX.call(obj)); //1
console.log(foo.getX.apply(obj)); //1
總結
-
bind()
方法會在調用時執行,而apply/call
則會立即執行函數 - 當參數固定時用
call
,不固定時用apply
,并且可以用arguments
來遍歷所有的參數