this

作者: ahong_吴 | 来源:发表于2017-01-17 17:32 被阅读27次
    • apply、call 有什么作用,什么区别
    • 两者都是为了改变函数体内的this指向。
    • 它们的不同之处是:apply接收参数数组,call接收接收参数列表。
      apply语法:fun.apply(thisObj,[arr1,arr2,arr3])
      call语法:fun.call(thisObj,Object)

    通俗点说:就是执行一个函数,然后把this和参数传进去。fun.call(this,参数1,参数2,参数...)

    • 以下代码输出什么?
    var john = { 
      firstName: "John" 
    }
    function func() { 
      alert(this.firstName + ": hi!")
    }
    john.sayHi = func
    john.sayHi() 
    

    输出 john:hi!

    • 下面代码输出什么,为什么
      func() 
    
      function func() { 
        alert(this)
      }
    

    输出:window 因为是window调用的func函数

    • 下面代码输出什么
         function fn0(){
             function fn(){
               console.log(this);
             }
           fn();
         }
    
       fn0();
    
       document.addEventListener('click', function(e){
         console.log(this);
         setTimeout(function(){
             console.log(this);
         }, 200);
    }, false);
    

    输出 window document window

    • 下面代码输出什么,why
    var john = { 
      firstName: "John" 
    }
    
      function func() { 
        alert( this.firstName )
    }
    func.call(john) 
    

    输出 john 因为利用了call this变成了john

    • 代码输出?
    var john = { 
      firstName: "John",
      surname: "Smith"
    }
    
     function func(a, b) { 
      alert( this[a] + ' ' + this[b] )
    }
    func.call(john, 'firstName', 'surname') 
    

    输出 john smith

    • 以下代码有什么问题,如何修改
    var module= {
    // var me = this;   //修改
      bind: function(){
        $btn.on('click', function(){
          console.log(this) //this指什么 $btn
          //me.showMsg();
        })
      },
      
      showMsg: function(){
        console.log('ahong');
      }
    }
    

    相关文章

      网友评论

          本文标题:this

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