美文网首页@IT·互联网
JavaScript的this相关问题

JavaScript的this相关问题

作者: 柏龙 | 来源:发表于2017-05-09 21:16 被阅读0次

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

  • 作用:
    都是为了改变某个函数运行时的上下文(context),改变函数体内部 this 的指向。
  • 区别:
    apply() 方法接受的是一个包含多个参数的数组
    call() 方法接受的是若干个参数的列表
var func = function(arg1, arg2) {
...
};
func.apply(this, [arg1, arg2]);
func.call(this, arg1, arg2);

bind() bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。

document.addEventListener('click', function(e){
    console.log(this);  // this 输出 #document 指向当前事件对象
    setTimeout(function(){
        console.log(this); //  bind(this) 得到新的函数 里面的this就是传递当前对象
    }.bind(this), 200);
}, false);

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

var john = { 
  firstName: "John" 
}
function func() { 
  alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi()
// john.sayHi() = func(),函数里的 this 指向 join对象,this.firstName = "John" , 输出结果:John: hi!

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

func() 
function func() { 
  alert(this)
}
// func() 里面的  this 不带表函数本身,this带表全局, 输出 [object Window]

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

document.addEventListener('click', function(e){
    console.log(this);
    setTimeout(function(){
        console.log(this);
    }, 200);
}, false);
// 第一个 this 输出 #document 指向当前事件对象,第二个 this 输出 Window setTimeout方法执行的函数this就是全局对象

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

var john = { 
  firstName: "John" 
}

function func() { 
  alert( this.firstName )
}
func.call(john)
func.call(john) 
// call() 第一个参数代表传入的当前this指向,所以 func() 里面的this就是传入的参数John。

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

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

方法一:

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

方法二:

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

相关文章

网友评论

    本文标题:JavaScript的this相关问题

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