call、callee、caller詳解

call

call用於改變函數指向。

call是Funcrion.prototype的屬性方法

function add(a, b) {
    console.log(this);
    return a + b;
}

add(1, 2);  //this=window,嚴格模式下爲undefined
add.call({ name: "新指向" }, 3, 4)  //this={ name: "新指向" }

callee

callee主要用於代替函數名,降低耦合性。

calleearguments對象的一個屬性,可以獲取函數自身。

//乘階函數
function chengjie(n) {
    if (n == 1) {
        return 1;
    }

    return n * chengjie(n - 1);
}

let result = chengjie(5);
console.log(result)

如上代碼:如果chengjie()的函數名稱變更了,那麼我也需要手動變更其內部使用的chengjie(n-1)。如果函數名被大量使用,那麼需要修改的地方就會很多。callee的作用就是讓函數名一改全改。

//乘階函數
function chengjie(n) {
    if (n == 1) {
        return 1;
    }

    return n * arguments.callee(n - 1);
}

//變更函數名
var jc = chengjie;
//回收chengjie函數
chengjie=null;
let result = jc(5);
console.log(result)

可以看出,我們變更了函數名後,jc仍是一個函數,而chengjie已經是一個null,無法正常執行了

caller

caller返回函數被誰調用了。

function add(a, b) {
    print(a + b);
}

function print(value) {
    console.log(print.caller)      //[Function: add],返回print被誰調用了
    console.log(value)              //3
}

add(1,2)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章