javascript 中arguments、call、apply、bind、callee、caller属性的简单理解

来源:互联网 发布:linux tee 命令 编辑:程序博客网 时间:2024/05/14 13:15
    //JS arguments的几种情况(函数被调用时才会被创建,否则为null)    //1、访问参数的个数    function test() {        alert(arguments.length)    }    test("hehe","jsjs");  //2    test();      //0    test(110);  //1
    //2、访问参数的值    function sayHi() {        alert(arguments[0])   //弹出222    }    sayHi(222,333);
    //3、模拟函数重载    function add() {        if(arguments.length === 1){            alert(arguments[0]+5)        }else if(arguments.length === 2){            alert(arguments[0]+arguments[1])        }    }    add(10);   //15    add(20,50);  //70
    //4、caller(在一个函数调用另一个函数时,被调函数会生成一个caller属性,指向调用它的函数对象)    function testCaller() {        var caller=testCaller.caller;        alert(caller)   //此时caller指的就是testCaller2这个函数    }    function testCaller2() {        testCaller()    }    testCaller2();
    //5、callee(是arguments的一个成员属性,当函数被调用时,arguments。callee指向函数本身)    function sum(n) {        if(n<=0){            return 0        }else{            return n+arguments.callee(n-1)        }    }    console.log(sum(10)) ;//55    //call和apply的区别(作用都是将函数对象绑定到另一个函数上,即将Obj.this绑定到this.obj上,    // 区别在于参数不同)    function ADD(a,b) {        console.log(a+b)    }    function plus(a,b) {        console.log(a-b);    }    ADD.call(plus,5,2) ; //7  实际上是ADD替换plus,执行ADD(5,2) 结果为7    ADD.apply(plus,[5,1]);  //6  两者作用是一致的,区别在于参数,一个直接传,一个存数组里    //bind :将函数绑定到另一个函数上,返回对应函数,留着调用(call和apply是立即执行)    var bar = function(){        console.log(this.x);    };    var foo = {        x:3    };    bar(); // undefined    var func = bar.bind(foo);    func();

阅读全文
0 0
原创粉丝点击