this

作者: GarenWang | 来源:发表于2016-12-15 21:11 被阅读208次

    简答题

    1.apply、call 有什么作用,什么区别

    • call apply,调用一个函数,传入函数执行上下文及参数,语法如下:
        fn.call(context,param1,param2,...)
        fn.apply(context,paramArray)
    
    • 相同点有
      1.产生的作用和效果相同
      2.必须至少有一个参数
      3.第一个参数必须有而且是一个对象
      4.如果没有提供 context,那么 Global 对象被用作 context。

    • 区别是传递的参数不同,call传入的一个一个的参数,而apply传入的是一个参数构成的数组。
      1 apply最多只能有两个参数,新this对象和一个数组 argArray。如果给该方法传递多个参数,则把参数都写进这个数组里面,即使只有一个参数,也要写进数组里面。如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数
      2 call:则是直接的参数列表,主要用在js对象各方法互相调用的时候,使当前this实例指针保持一致,或在特殊情况下需要改变this指针。如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

    • 下面简单的demo
      function person(name,age){
      this.name=name;
      this.age=age;
      this.money=500;
      }
      function myFun(money){
      //此时函数内的this为全局对象window.money
      alert(this.money)
      }
      var money=100;//window.money
      myFun(money);//执行结果调用的全局变量money,为100.
      若使用apply和call也能实现弹出100的效果
      //等同于如下:
      myFun.apply(window);//100
      myFun.call(window);//100
      但是我们要想得到person函数里的money,则要使用call,apply
      //若我想出现person函数的money,可以使用apply
      myFun.apply(person('李四','20'))//500
      myFun.apply(person('李四','20'),[])//500
      myFun.call(person('李四','20'))//500

    • 原因是此时myFun方法里面的this指向的是person('李四','20')对象,二不是myFun类(函数),故弹出500.

    • call,apply其实质就是改变this的作用域,this 默认情况下为全局作用域。

    • apply,this的实例和技巧,可以看看这篇文章
      apply()用法和call()的区别

    代码题

    1.以下代码输出什么?

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

    结果输出:"John: hi!",分析如下:

        john.sayHi = func 
        //使John对象变为了
        var john= {
            firstName:'John',
            sayHi:func
        }
        //这里对象john调用的func函数,这里this就是对象john。
        john.sayHi() //输出结果为:"John:hi!"
    

    2. 以下代码的输出结果

    func() //弹出:[object Window]
    
        function func() { 
          alert(this)//this默认情况下为全局对象window
        }
    
    • func函数是在全局作用域下被调用的,func的this为Window对象

    3. 以下代码的输出结果

      function fn0(){
            function fn(){
                console.log(this);  //window
            }
            fn();
        }
    
        fn0(); 
    
        document.addEventListener('click', function(e){
            console.log(this);  //#Document
            setTimeout(function(){
                console.log(this);  //window
            }, 200);
        }, false);
    
    • 第一个this输出结果为window ,因为在函数被直接调用时this绑定到全局对象。在浏览器中,window就是该全局对象
    • 第二个this输出结果为#document,因为函数调用时this绑定到了document。
    • 第三个this输出结果为window,因为setTimeout,setInterval两个方法的执行上下文与调用他们的函数的执行上下文是分离的,这两个方法执行的函数this也是全局对象。

    4下面代码输出什么,why

        var john = { 
          firstName: "John" 
        }
    
        function func() { 
          alert( this.firstName )
        }
        func.call(john) //输出结果为john
    
    • 原因是func.call(john),改变了func函数执行的作用域,使全局的作用域改变为john对象的作用域,此时的this指向对象john,所以结果:this.firstName等同于John.firstName,输出结果为John

    5下面代码输出什么,why

      var john = { 
          firstName: "John",
          surname: "Smith"
        }
    
        function func(a, b) { 
          alert( this[a] + ' ' + this[b] )
        }
        func.call(john, 'firstName', 'surname') //"John Smith"
    
    • 原因func.call(john, 'firstName', 'surname')指定了func函数在对象john里执行,此时传入的其余两个参数代表a和b,此时this.[a] 等同于john.firstName,this.[b]等同于john.surname.

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

    var module= {
          bind: function(){
            $btn.on('click', function(){
              console.log(this) //this指什么,指的是$btn
              this.showMsg();
            })
          },
          
          showMsg: function(){
            console.log('饥人谷');
          }
        }
    
    • 由于this指向的是$btn,那么接下来执行this.showMsg()会报错,因为$btn下没有showMsg这个方法,它在对象module上,

    • 修改的思路就是让this指向对象module,
      方法1
      //直接使用module调用
      var module= {
      bind: function(){
      $btn.on('click', function(){
      console.log(this) //this指什么,指的是$btn
      module.showMsg();
      })
      },

          showMsg: function(){
            console.log('饥人谷');
          }
        }
      

    方法2
    //利用变量储存当前的this的值
    var module= {
    bind: function(){
    var cur=this;
    $btn.on('click', function(){
    console.log(this) //this指什么,指的是$btn
    cur.showMsg();
    })
    },

          showMsg: function(){
            console.log('饥人谷');
          }
        }
    

    7 下面代码的输出结果

      var length = 3;
        function fa() {
          console.log(this.length);
        }
        var obj = {
          length: 2,
          doSome: function (fn) {
            fn();
            arguments[0]();
          }
        }
        obj.doSome(fa)//输出结果为3,1
    
    • 当执行obj.doSome(fa)时,也就变成了执行function (fa){fa(); arguments0;} 执行函数内部的法fa(),由于fa的执行环境this是window,var length = 3 等同于 window.length =3, 所以弹出结果为3
    • 而当执行到arguments0时,执行也是调用fa(),但是调用的对象是arguments自身,此时this.length 等同于 argument.length,由于arguments是一个类数组对象,只有一个参数,所以长度为1

    版权为饥人谷和作者所有,若转载请注明出处

    相关文章

      网友评论

      • 盒子爱上猫:恭喜呀~被评为饥人谷优秀博客,继续加油哦 :+1:

      本文标题:this

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