美文网首页
JavaScript中的callee, caller, call

JavaScript中的callee, caller, call

作者: js好难学啊 | 来源:发表于2018-08-29 23:04 被阅读0次

    2018/08/29 21:39

    callee, caller, call

    1. callee

    在函数内部,有两个特殊对象: arguments和this,arguments中保存着函数参数,这个对象还有一个 叫callee的属性,该属性是一个指针,指向拥有这个arguments对象的函数。

    function factorial (num) {
      if (num <= 1) {
        return 1
      } else {
        return num * arguments.callee(num-1)
      }
    }
    

    可以在函数内部使用arguments.callee获取这个函数的指针。
    这样做的好处是可以降低函数的耦合度。

    2. caller

    这个属性中保存着调用当前函数的函数的引用。

    function testCaller () {
        console.log(arguments.callee.caller)
    }
    
    function test () {
        testCaller()
    }
    
    test()
    ---------------
    结果:
    ƒ test() {
        testCaller();
    }
    

    3. call

    当谈到call这个方法时,顺便可以提及apply方法。

    这两个方法的用途都是在特定的作用域中调用函数,实际上就是设置函数体内this对象的值

    3.1 apply

    apply()方法接受两个参数
    => 1. 是在其中运行的函数的作用域
    => 2. 参数列表,[ Array实例 , arguments对象]

    3.2 call

    call()与apply()方法作用相同,但是接受的参数不同
    接受的参数
    => 1. 是在其中运行的函数的作用域
    => 2. 其余参数都直接传递给函数

    环境在node8 下
    --------------------
    this.a = 'windowName'
    this.o = {a: 'oName'}
    
    function getA() {
        console.log(this.a)
    }
    
    getA.apply(this) //windiwName
    getA.apply(this.o) //oName
    
    getA.call(this) //windiwName
    getA.call(this.o) //oName
    

    2018/08/29 23:05
    =============================更新=======================
    2018/09/01 22:00

    4.补充一个bind()方法

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

            var nameTest = 'windowName'
            var a = {
                nameTest: 'aName',
            }
            function f1 () {
                console.log(this.nameTest)
            }
    
            f1() //windowName
            let f1Bind = f1.bind(a)
            f1Bind() //aName
    

    综上所述呢, 通过js函数方法改变对象内部this指向有 apply, bind, call!

    2018/09/01 22:16

    相关文章

      网友评论

          本文标题:JavaScript中的callee, caller, call

          本文链接:https://www.haomeiwen.com/subject/giclwftx.html