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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章