call()
方法使用乙個指定的this
值和單獨給出的乙個或多個引數來呼叫乙個函式。
function list()
list(1, 2, 3, 4, 5); // [1]
陣列的所有方法都是掛在array
的prototype
上的,如圖:
而類陣列物件本身是沒有這些方法的,當然也無法呼叫:
那麼想在一些物件上呼叫這個物件本身沒有的方法就可以用call
方法,以下圖為例:
nodelist
是乙個類陣列物件它本身沒有slice
方法,所以呼叫的時候是undefined
。
array.prototype.slice.call(nodelist, 0, 1)
這段**就相當於nodelist.slice(0, 1)
。
因為nodelist
沒有slice
方法而array.prototype
有,那麼就在array.prototype
上呼叫slice
方法,並且使用call
方法讓slice
作用在nodelist
上,call
方法的後兩個引數就當作slice
的引數傳入。
當然,使用.slice.call(nodelist, 0, 1)
也是一樣的,只要slice
前面的物件上有slice
這個方法就可以。
var array = ['a', 'b'];
var elements = [0, 1, 2];
console.info(array); // ["a", "b", 0, 1, 2]
var numbers = [1, 3, 5, 7, 19];
bind()
方法建立乙個新的函式,在呼叫時設定this
關鍵字為提供的值。並在呼叫新函式時,將給定引數列表作為原函式的引數序列的前若干項。
var module =
}var unboundgetx = module.getx;
unboundgetx(); // undefined
var boundgetx = unboundgetx.bind(module);
boundgetx(); // 42
參考
function.prototype.call()
function.prototype.bind()
call apply bind簡單理解
js函式涉及到作用域時,函式定義時作用域以及很多東西無法確定,只有呼叫它時才能確定 作用是改變執行時上下文 作用域,即this 但是很多部落格解釋的非常複雜,這個解釋比較清楚,直接上 上下兩段 等價。function add c,d const obj console.log add.call ob...
call apply bind函式的理解以及手寫。
1 相同點,這三個是乙個函式。函式。函式。都可以改變函式的this指向 第乙個引數都是this要指向的物件。例如 var obj function funcall a,b,c funcall.call obj,a b c call函式 特點 1 可以改變當前函式的this指向 就是改變函式的呼叫者 ...
call, apply, bind方法詳解
function a x,y var c a.call c,5,6 5 6 arguments 5,6 再看例子 function person age,male var person1 person.call person1,20,female person1 var person var per...