this是一个关键字,表示执行当前函数的对象
- this永远跟着当前函数走,
- 永远是一个对象,
- 永远在函数执行时才能确定。
1. 默认绑定:没有明确被隶属对象执行的函数,this指向window
function fn(){
console.log(this); //window
console.log(typeof this); //object
}
fn();
- 严格模式下,this指向undefiend
"use strict";
function fn(){
console.log(this); //undefined
}
fn();
2. 隐式绑定:明确被隶属对象执行的函数,this指向执行对象
var obj = {
fn:function(){
console.log(this);
}
}
obj.fn(); //this指向obj
- 隐式丢失:某函数被当做参数传递给另一个函数,则会丢失原本的执行对象,指向window
var obj = {
fn:function(){
console.log(this);
}
}
function test(cb){
cb();
}
test(obj.fn); //this指向window
- 注意:不是所有的回调函数中this都指向window,某些特定情况下被系统修改了。
document.addEventListener("click",function(){
console.log(this); //this指向document
});
3. 显示绑定(强制绑定):利用函数的方法改变this的指向(解决了this隐式丢失的问题)
例1:
function fn(a){
console.log(this);
console.log(typeof this); //object
}
fn.call("hello"); //this指向hello
例2:针对上方隐式绑定的隐式丢失问题,可以这样解决
var obj = {
fn:function(){
console.log(this);
}
}
function test(cb){
cb.call(obj); //this指向obj
}
test(obj.fn);
4. new绑定:函数被new执行后,函数内部的this指向new出的实例
function Fn(){
console.log(this);
console.log(typeof this); //object
}
new Fn(); //this指向Fn{}