JavaScript面试题:如何理解 JS 中的this关键字?

2019-06-2007:51:03WEB前端开发Comments3,131 views字数 891阅读模式

1.如何理解 JS 中的this关键字?

JS 初学者总是对 this 关键字感到困惑,因为与其他现代编程语言相比,JS 中的这this关键字有点棘手。 “this” 一般是表示当前所在的对象,但是事情并没有像它应该的那样发生。JS中的this关键字由函数的调用者决定,谁调用就this就指向哪个。如果找不到调用者,this将指向windows对象。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/13689.html

来几个粟子文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/13689.html

第一个例子很简单。 调用 test对象中的 func(),因此func() 中的'this'指向的是 test 对象,所以打印的 proptest 中的 prop,即 42文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/13689.html

var test = {
 prop: 42,
func: function(){
 return this.prop;
},
 };
console.log (test.func()); // 42
复制代码

如果我们直接调用getFullname函数,第二个例子将打印出'David Jones',因为此时 this 找不到调用者,所以默认就为 window 对象,打印的 fullname 即是全局的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/13689.html

var fullname = ‘David Jones’
var obj ={
fullname: ‘Colin Brown’,
prop:{
  fullname:’Aurelio Deftch’,
  getFullname: function(){
    return this.fullname;
  }
 }
}
var test = obj.prop.getFullname
console.log(test()) // David Jones
obj.prop.getFullname() // ‘Aurelio Deftch’ 
复制代码

2. 由于 this 关键字很混乱,如何解决这个问题

有很多方法可以解决这个问题; 但是,无论你选择哪种解决方案,最重要的是要知道你决定让 this 指向哪个对象。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/13689.html

一旦你弄清楚了this指向的对象,你就可以直接将它改成对象名。 否则,使用bindcallapply函数也可以解决问题。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/13689.html

作者:前端小智
链接:https://juejin.im/post/5d0976c66fb9a07efa091bcf
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/13689.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/13689.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/13689.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定