美文网首页
this 相关问题

this 相关问题

作者: 辉夜乀 | 来源:发表于2017-05-15 22:34 被阅读30次

    问题1: apply、call 、bind有什么作用,什么区别

    • apply
    fn.apply(context, [parm1, parm2, parm3])
    /*调用函数,只接受2个参数,
    第一个context是函数的执行上下文,内部的 this 指向 context
    第二个是一个数组,里面包含传递进去的参数
    */
    
    • call
    fn.call(context, parm1, parm2, parm3)
    /*调用函数,能接受多个参数,
    第一个context是函数的执行上下文,内部的 this 指向 context
    后面的都是传递进去的参数
    */
    
    • bind
    fn.bind(context)
    /*返回一个函数,新函数的执行上下文为context 
    只接受一个参数,新函数内的this指向context
    */
    

    问题2: 以下代码输出什么?

    var john = { 
      firstName: "John" 
    }
    function func() { 
      alert(this.firstName + ": hi!")
    }
    john.sayHi = func
    john.sayHi()
    
    //John:hi!
    

    问题3: 下面代码输出什么,为什么

    func() 
    function func() { 
      alert(this)
    }
    
    /*window
    原因:
    this指的是,调用函数的那个对象,func 函数的调用对象为 window
    --另一种解释--
    func() 等价为 func.call(undefined)
    当传入的 context 为 undefined 或 null 时,window 对象就是默认的 context
    this 就是 window
    */
    

    问题4:下面代码输出什么

    document.addEventListener('click', function(e){
        console.log(this);
        setTimeout(function(){
            console.log(this);
        }, 200);
    }, false);
    
    /*document  window
    this 指的是,调用函数的那个对象
    addEventListener 函数的调用对象是 document,所以第一个 this 是 document
    setTimeout 函数的调用对象是window,所以第二个 this 是 window
    */
    

    问题5:下面代码输出什么,why

    var john = { 
      firstName: "John" 
    }
    function func() { 
      alert( this.firstName )
    }
    func.call(john)
    
    /*John
    func 函数用call方法调用,第一个参数就是this,
    func 函数内的 this.firstName 就是john.firstName,也就是 John
    */
    

    问题6: 以下代码有什么问题,如何修改

    var module= {
      bind: function(){
        $btn.on('click', function(){
          console.log(this)     //this指什么,this指$btn
          this.showMsg();       //这个this指的是$btn
        })
      },
      
      showMsg: function(){
        console.log('饥人谷');
      }
    }
    
    /*会报错,因为代码中的 this.showMsg() 这个 this 是指 $btn 而不是对象 module,
    $btn 上没有 showMsg 这个方法,所以会报错
    */
    

    修改代码

    //修改代码,把指向module对象的this保存起来
    var module= {
      bind: function(){
        var _this = this        //把指向module对象的this保存起来
        $btn.on('click', function(){
          console.log(this)     //this指什么,this指$btn
          _this.showMsg();      //_this为module对象
        })
      },
      
      showMsg: function(){
        console.log('饥人谷');
      }
    }
    

    相关文章

      网友评论

          本文标题:this 相关问题

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