第三十三弹-this、闭包

一、问答

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

call和apply都能改变执行上下文(this的指向),它们唯一的区别是传递参数的方式不同,call是一个一个的传递参数,而apply是传递一组数组或者类数组对象作为参数
示例:
apply

      function getMin(){
        return Math.min.apply(null,arguments); //这里我们无法确切知道参数是几个,使用apply
      }
      console.log(getMin(1,2,3,4));     //1

call

      function join(str){
        return Array.prototype.join.call(str);   //参数只有一个,是确定的使用call
      }
      console.log(join("hello"))    //  "h,e,l,l,o"  

二、代码

1.当函数作为对象的方法调用时 this指代当前对象

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

2.在函数被直接调用时this绑定到全局对象

        func()
      function func() {
        alert(this)    // [object Window]
      }

3.内部嵌套函数的this不是父函数 而是全局对象

      function fn0(){
          function fn(){
              console.log(this);      //Window
          }
          fn();
      }
      fn0();

4.在事件处理程序中this代表事件源DOM对象(低版本IE有bug,指向了window)
setTimeout和setInterval 这两个方法执行的函数this也是全局对象

      document.addEventListener('click', function(e){
          console.log(this);                                  //document
          setTimeout(function(){
              console.log(this);                               //Window
          }, 200);
      }, false);
  1. call函数的第一个参数就是函数执行上下文,就是this的值
      var john = {
        firstName: "John"
      }

      function func() {
        alert( this.firstName )            //join
      }
      func.call(john)

6.call函数的第二个参数以后就是func的入参

      var john = {
        firstName: "John",
        surname: "Smith"
      }

      function func(a, b) { 
        alert( this[a] + ' ' + this[b] )
      }
      func.call(john, 'firstName', 'surname')   // "John Smith"

7.以下代码有什么问题,如何修改?

      var module= {
        bind: function(){
          $btn.on('click', function(){
            console.log(this) //this指什么 this指代的是$btn 
            this.showMsg();
          })
        },
        showMsg: function(){
          console.log('饥人谷');
        }
      }

this.showMsg()中的this指代的$btn 而不是module,应改为

      var module= {
        bind: function(){
          var me=this;
          $btn.on('click', function(){
            me.showMsg();
          })
        },
        showMsg: function(){
          console.log('饥人谷');
        }
      }

参考文档:
饥人谷课件-this
阮一峰blog


本教程版权归小韩同学和饥人谷所有,转载须说明来源

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. apply、call 、bind有什么作用,什么区别? call ,apply的作用:调用一个函数,传入函数...
    Rising_suns阅读 403评论 0 0
  • 作业 this 相关问题 问题1: apply、call 有什么作用,什么区别apply()和call()函数都可...
    饥人谷_桶饭阅读 401评论 0 0
  • apply、call 有什么作用,什么区别 使用call和apply方法,可以改变对象方法的运行环境。 call ...
    coolheadedY阅读 355评论 0 0
  • 简答题 1.apply、call 有什么作用,什么区别 call apply,调用一个函数,传入函数执行上下文及参...
    GarenWang阅读 551评论 1 4
  • this对象是在运行函数时基于函数的运行环境绑定的;全局环境中,this对象就是window,而当函数被作为某个对...
    闪电西兰花阅读 122评论 0 0