this指针面试题
machao07 opened this issue · comments
马超 commented
this指向有哪几种情况
- 全局作用域或者普通函数自执行中this指向
全局对象window
- 事件函数内部的this指向事件源:注意在事件函数中如果包含普通函数,普通函数自执行后,内部this还是指向
window
- 对象方法调用时,this指向
调用的对象
1、普通函数中的this
this是JavaScript的一个关键字,指函数执行过程中,自动生成的一个内部对象,是指当前的对象,只在当前函数内部
使用。
(this对象是在运行时基于函数的执行环境绑定的:在全局函数中,this指向的是window;当函数被作为某个对象的方法调用时,this就等于那个对象)
//全局作用域
console.log(this); //Window
//普通函数
function fn(){
console.log(this); //Window
}
2、事件函数中的this指向事件源
document.body.onclick = function(){
this.style.height = "1000px";
console.log(this); //body对象
function fn(){
console.log(this); //Window
}
fn(); //函数加括号调用叫函数自执行,函数自执行时,内部的this指向顶层对象/window
};
3、对象方法调用时,this指向调用的对象
let obj = {
name : "lanlan",
fn : function(){
console.log(this)
},
lacy:{
name : "didi",
fn : function(){
let num = 10;
console.log(this)
}
}
};
obj.fn(); //obj
obj.dudu.fn(); //lacy
4、类实例来调用函数时,this指向实例
class B {
fn() {
console.log(this)
}
}
var b = new B()
var fun = b.fn
b.fn() // 指向 b
fun() // undefined
Tips:ES6 下的 class 内部默认采用的是严格模式,fun不会指定全局对象为默认调用对象
5、 ES6箭头函数的this
- 箭头函数中的this始终指向箭头函数定义时的离this最近的一个函数,如果没有最近的函数就指向window
- 箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的。简单的说,函数在定义时,this就继承了定义函数的对象。