this

作者: coolheadedY | 来源:发表于2016-09-21 00:23 被阅读27次
    • apply、call 有什么作用,什么区别

    • 使用call和apply方法,可以改变对象方法的运行环境。

    • call 和 apply 都可以改变函数执行时的上下文环境,也就是指定了函数体内部 this 的指向。

    • call 和 apply 的区别:call和apply区别在于接受参数的形式不同。
      function.call(obj,arg1,arg2,arg3, ...);接受逐个参数
      function.apply(obj,[arg1,arg2..]);接受的是数组形式的参数

    • this最直白的解释(新增待填)

    • 以下代码输出什么?

    var john = { 
      firstName: "John" 
    }
    function func() { 
      alert(this.firstName + ": hi!")
    }
    john.sayHi = func
    john.sayHi() //John:hi!
    
    • 可以理解成对象john添加了一个sayHi的属性,对象john在sayHi方法里执行了func().所以this环境是对象john
    var john = { 
      firstName: "John" ;
      sayHi: function func() { 
              alert(this.firstName + ": hi!")
            }
    }
    
    • 下面代码输出什么,为什么
        func();//输出对象window,因为函数func()在window对象调用执行的
    
        function func() { 
          alert(this);
        }
    
    • 下面代码输出什么
    function fn0(){
        function fn(){
            console.log(this);//输出window对象
        }
        fn();
    }
    fn0();//window
    document.addEventListener('click', function(e){
        console.log(this);// 输出绑定事件的这个document对象
        setTimeout(function(){
            console.log(this);//输出window对象
        }, 200);
    }, false);
    //点击document后
    //document
    //window
    
    • 下面代码输出什么,why
    var john = { 
      firstName: "John" 
    }
    function func() { 
      alert( this.firstName )
    }
    func.call(john) //输出John,这里用call函数改变func执行的作用域,使函数func在john对象中执行被调用.
    
    • 代码输出?
    var john = { 
      firstName: "John",
      surname: "Smith"
    }
    function func(a, b) { 
      alert( this[a] + ' ' + this[b] )
    }
    func.call(john, 'firstName', 'surname') //输出John Smith,这里用call函数改变func执行的作用域并传递两个参数,指定执行john对象下向对应的方法
    
    • 以下代码有什么问题,如何修改
    var module= {
      bind: function(){
        $btn.on('click', function(){
          console.log(this) //this指什么
          this.showMsg();
        })
      },
      
      showMsg: function(){
        console.log('饥人谷');
      }
    }
    

    修改如下

    var module= {
      var _this = this//用局部变量_this把this保存下来以便后面使用
      bind: function(){
        $btn.on('click', function(){
          console.log(_this) //this指的是被绑定事件的$btn对象
          _this.showMsg();//使用局部变量_this执行module对象下的方法
        })
      },
      
      showMsg: function(){
        console.log('饥人谷');
      }
    }
    

    本博客版权归 本人和饥人谷所有,转载需说明来源

    相关文章

      网友评论

          本文标题:this

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