在不使用箭头函数和call、apply、bind的情况下,这些this的指向,当我们调用函数的时候是确定的。调用函数的不同决定了this指向的不同。
调用方式 | this指向 |
---|---|
普通函数 | 严格模式下是undefined,正常模式是Window |
表达式函数 | 严格模式下是undefined,正常模式是Window |
构造函数 | 实例对象 |
对象方法调用 | 该方法所属的对象 |
事件绑定方法 | 当前事件所绑定的对象 |
定时器函数 | Window |
立即执行函数(自调用函数) | 严格模式下是undefined,正常模式是Window |
普通函数
正常模式:this指向Window
function fn () {
console.log(this) //Window
}
fn();
严格模式:this不知道指向谁,所以打印undefined
function fn () {
'use strict'
console.log(this) //undefined
}
fn();
表达式函数
严格模式下this是undefined,正常模式是Window
let fn = function() {
console.log(this) //Window
}
fn();
构造函数
构造函数的this指向实例对象,下例指向实例对象fn
function Fn(name) {
this.name=name;
console.log(this) //Fn {name: "constructor function"}
}
let fn = new Fn('constructor function');
对象方法调用
对象调用自身方法时的this指向该方法所属的对象
let obj = {
name:'zy',
sayHi:function() {
console.log(this)
}
}
obj.sayHi() //obj {name: "zy", sayHi: ƒ}
事件绑定方法
事件绑定时,this指向当前事件所绑定的对象
<!-- html -->
<button>点我</button>
//js
let btn = document.querySelector('button');
btn.onclick = function() {
console.log(this) //<button>点我</button>
}
定时器函数
定时器里的函数是回调函数,所有回调函数的this都指向Window
setTimeout(function(){
console.log(this) //Window
},1000)
立即执行函数(自调用函数)
严格模式下this是undefined,正常模式是Window
(function(){
'use strict'
console.log(this) //undefined
})()