深入理解js中的apply call bind

2022-08-23 21:06:09 字數 1628 閱讀 2009

var student = 

function getname(firstname , lastname)

call 方法第乙個引數也是作為函式上下文的物件,但是後面傳入的是乙個引數列表,而不是單個陣列。

var student = 

function getname(firstname , lastname)

getname.call(student , 'mq' , 'jj'); //mq xiaoming jj

1.陣列合併

var arr_1 = [1,2,3];

var arr_2 = [4,5,6];

console.log(arr_1) //[1,2,3,4,5,6]

2.獲取陣列中的最大值和最小值

var num_arr = [3,5,8,1,9];

var min_num = math.min.call(math , 3 , 5 , 8 , 1 , 9)

console.log(max_num) //9

console.log(min_num) //1

3.類(偽)陣列使用陣列方法

var domnodes = array.prototype.slice.call(document.getelementsbytagname("*"));

bind()方法會建立乙個新函式,稱為繫結函式,當呼叫這個繫結函式時,繫結函式會以建立它時傳入 bind()方法的第乙個引數作為 this,傳入 bind() 方法的第二個以及以後的引數加上繫結函式執行時本身的引數按照順序作為原函式的引數來呼叫原函式。

var foo = );

}}

使用bind解決儲存this的問題

var foo = .bind(this));

}}

bind引數的使用:

var student = 

function getname(firstname , lastname)

var getbindname = getname.bind(student,'lihui');

getname('mrs','jj'); //mrs jj

getbindname(); //lihui xiaoming undefined

getbindname('jj'); //lihui xiaoming jj

getbindname('mrs','jj'); //lihui xiaoming mrs

getname.call(student,'lihui') //lihui xiaoming undefined

call 是把第二個及以後的引數作為 getname方法的實參傳進去,而 getbindname方法的實參實則是在 bind 中引數的基礎上再往後排。

var student = 

var studentinfo =

}console.log(studentinfo.getage.bind(student)()); //18

console.log(studentinfo.getage.call(student)); //18

js深入理解 一

1if a b 兩者等價 a b alert hello word 2.給eval取別名var a 111 var b eval var c b a alert c 輸出 111 3.刪除元素 不能刪除 var語句宣告的變數 var o delete o.x alert o.x 輸出 undefin...

js深入理解(二)

1.函式閉包var scope global scope function checkscope return f checkscope 輸出local scope var scope global scope function checkscope return f checkscope 輸出lo...

js深入理解(三)

1.物件的三個屬性 原型屬性 object.getprototypeof a 獲取a的原型 a.constructor.prootype 獲取a的原型 推薦 o.isprototypeof a 判讀o是否是a的原型 類屬性 function classof o classof o 輸出object ...