1. 程式人生 > >call() 、 apply() 、bind()方法

call() 、 apply() 、bind()方法

Function.apply(obj,[])方法能接收兩個引數:
obj:這個物件將代替Function類裡this物件
args:這個是陣列,apply方法把這個集合中的元素作為引數傳遞給被呼叫的函式。

Function.call(obj,arg1,ar2,arg3,...)方法能接收兩個引數:
obj:這個物件將代替Function類裡this物件
argi:後面是可變引數,call方法把這些引數作為引數傳遞給被呼叫的函式。

Function.bind(obj,arg1,ar2,arg3,...)();方法能接收兩個引數:
obj:這個物件將代替Function類裡this物件
argi:後面是可變引數,call方法把這些引數作為引數傳遞給被呼叫的函式。

它們都可以改變函式體內部 this 的指向。bind是返回對應函式,沒有立即呼叫,apply、call是立即呼叫。
判斷型別:

console.log(Object.prototype.toString.call(123)) //[object Number]
console.log(Object.prototype.toString.call('123')) //[object String]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(function(){})) //[object Function]