this

作者: YQY_苑 | 来源:发表于2019-08-18 10:44 被阅读0次

    JS四种声明函数的方式

    // 最少见的声明方式:
    // 用字符串标识函数(前面为参数,最后为函数体)
    const f1 = new Function( 'x' ,'y', 'return x+y' )
    
    //函数声明
    function f2(x,y){
      return x+y;
    }
    
    // 声明匿名函数  , 并赋值给f3
    const f3 = function(x,y){
      return x+y;
    }
    
    // 箭头函数
    (x,y) => x+y
    
    
    // 前三是ES6之前的语法,支持this/ garguments / new
    // 最后一个箭头函数是ES6新出的语法,不支持 this/ arguments /mew
    

    箭头函数this无法指定,只有环境决定

    image.png

    this

    函数的返回值是由什么确定

    1. 调用使得输入参数:params
    2. 定义是的环境 env

    this是参数还是环境决定??

    this参数决定的, 所以this是什么需要看调用时的参数

    // 显式
    fn.call( asThis, 1, 2 )
    cn.bind( asThis, 1, 1 )
    obj.method.call( obj, 'hi' )
    
    // 隐式
    
    fn(1, 2)
    // fn.call(undefined, 1, 2)
    
    obj.method('hi')
    // obj.method.call(obj, 'hi')
    
    array[0]('hi')
    // array[0].call(array, 'hi')
    
    button.onclick = function(){
      console.log(this)
    }
    
    // 点击button时,this => button
    
    
    // 自己调用自己时,this,看参数
    var f = button.onclick
    f()  // this => windows
    
    f.call( ' b ')   // this => b
    
    // 答:此时无法判断this是什么,需要看是怎么调用的。
    
    

    面试题

    image.png
    let length = 10  
     //  用let声明的变量不会挂载windows上
    //   此时用var ,下面windows.length = 10
    
    function fn(){
    //   this => windows => windows.length => 当前页面有多少个窗口【iframe】
    //   this => arguments => arguments.length = 2   【实参的长度】
        console.log(this.length)  
    }
    
    let obj = {
      length :5,
      method(fn){
          fn()   //   这里匿名调用相当于 直接调用外层的fn
          arguments[0]()    //  相当于上面array的调发
      }
    }
    
    obj.method( fn, 1)  
    
    image.png image.png

    总结

    • 函数的返回值由参数和环境确定
    • this是参数,arguments也是参数
    • 全局变量和自由变量是环境

    相关文章

      网友评论

          本文标题:this

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