call, bind,apply 的區別?
阿新 • • 發佈:2020-12-21
技術標籤:js
call, bind,apply 的區別?
call 和 apply 調他們既可以改變函式 this 的指向,傳遞引數 和 呼叫函式;
他們只有一個區別,就是引數的格式,call 是一個一個數,apply 是一個數組;
bind 他呢,也和 call , apply 一樣,只是 不會自動呼叫函式;
call
:
功能:呼叫函式,傳遞引數,改變函式的 this
指向;
結構:
fn.call(this的指向,傳遞的引數)
使用:
function fn (x, y) {
console.log(this);
console.log(x, y);
}
let o = {
name: 'zyf'
}
// 呼叫 fn 函式, 改變 fn 的this為 o, 傳入引數 1 和 2;
fn.call(o, 1, 2);
bind
:
概念: bind()
方法,返回一個 新函式,呼叫 bind 時,新函式的 this 指向 bind
的第一個引數,剩餘引數,就當新函式的引數了 。
功能:改變函式的 this
指向,傳遞引數,不會呼叫函式;
結構:
fn.bind(this的指向,傳遞的引數);
使用:
function fn (x, y) {
console.log(this);
console.log(x, y);
}
let o = {
name: 'zyf'
}
// 使用 bind ,然後呼叫函式;
fn.bind(o, 1, 2)();
// 使用 bind 返回值為一個新陣列
let newFn = fn.bind(o, 1, 2);
newFn(); // 執行相關和上面的一樣
apply:
效果和 call()
一樣,只不過,他的第二個引數,傳遞引數時,是一個數組;
結構:
fn.apply(this的指向,[引數1,引數2,.....])
使用:
function fn (x, y) {
console.log(this);
console.log(x, y);
}
let o = {
name: 'zyf'
}
fn.apply(o,[1, 2]);