this指向是工做和面试中常常会遇到的问题。面试
根据我的理解,简单从3个方面来总结一下this的指向问题。函数
1. 如果全局函数,而且没有直接调用它的对象,没有严格模式,则默认指向全局window
或global
2. 如果全局函数,而且没有直接调用的对象,严格模式下,this
指向undefined
3. 箭头函数的this
,是在函数定义时根据上下文函数决定的。如果全局定义,则this
指向window
或global
。若上下文有函数环境,则指向该上下文的this
4. 使用call
改变this
的指向取决于call
的第一个参数,若第一个参数是null
,仍是会绑在全局的
this
指向结合下面的示例加深理解。this
(1) 如果全局函数,而且没有直接调用它的对象,没有严格模式,则默认指向全局
window
function hello1(){ console.log('我是hello1 this:',this) // window } hello1()
(2)如果全局函数,而且没有直接调用的对象,严格模式下,this
指向undefined
function hello2(){ 'use strike'; console.log('我是hello2 this:',this) // undefined } hello2()
(3)用obj
直接调用hello3
函数,则第一个this
指向obj
。
setTimeOut
里面的箭头函数,this
指向obj
。
setTimeOut
里面的匿名函数,this
指向window
。
由于:箭头函数的this,是在定义箭头函数时根据上下文函数环境决定,该箭头函数定义在函数内部,上下文执行环境在hellow3函数内,因此指向hello3的this
var obj = { name:'aaa', hello3(){ console.log('我是hello3 this:',this); // obj setTimeout(()=>{ console.log('我是hello3 里面箭头函数settimeout this:',this); // obj },3000) setTimeout(function (param) { console.log('我是hello3 里面匿名函数settimeout this:',this); // window },2000) } } obj.hello3()
(4)hello4
是普通函数,直接被obj
调用,则this
执行obj
。hello5
是箭头函数,this
应该指向上限文函数中的this
,这里上下文没有函数对象,因此默认为window
var obj2 = { name:'aaa', hello4(){ console.log('我是hello4 this:',this); // obj }, hello5:()=>{ console.log('我是hello5 this:',this); // window }, } obj2.hello4(); obj2.hello5();
(5)使用call
绑定this
,取决于call
的第一个参数,若第一个参数是null
,仍是会绑在全局的。
function foo(){ console.log(this) } foo(); // global foo.call(1); // [Number: 1] foo.call({a:10},1); // { a: 10 } 1. foo.call(null,1); // global