JavaScript面试题:如何理解 JS 中的this关键字?
1.如何理解 JS 中的this
关键字?
JS 初学者总是对 this
关键字感到困惑,因为与其他现代编程语言相比,JS 中的这this
关键字有点棘手。 “this” 一般是表示当前所在的对象,但是事情并没有像它应该的那样发生。JS中的this
关键字由函数的调用者决定,谁调用就this
就指向哪个。如果找不到调用者,this
将指向windows
对象。
来几个粟子
第一个例子很简单。 调用 test
对象中的 func()
,因此func()
中的'this'指向的是 test
对象,所以打印的 prop
是 test
中的 prop
,即 42
。
var test = {
prop: 42,
func: function(){
return this.prop;
},
};
console.log (test.func()); // 42
复制代码
如果我们直接调用getFullname
函数,第二个例子将打印出'David Jones'
,因为此时 this
找不到调用者,所以默认就为 window
对象,打印的 fullname
即是全局的。
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
指向哪个对象。
一旦你弄清楚了this
指向的对象,你就可以直接将它改成对象名。 否则,使用bind
,call
,apply
函数也可以解决问题。
作者:前端小智
链接:https://juejin.im/post/5d0976c66fb9a07efa091bcf
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
THE END