1.全局作用域下,指定是全局对象,浏览器下是window,在node.js(开源、跨平台的js服务器运行环境)环境下是global。
console.log(this)
输出为window
2.函数内部
2.1直接调用(非严格模式下为window,严格模式为undefined)
严格模式:(加use strict)
function func(){
'use strict'
console.log(this)
}
func()
非严格模式:
function func(){
// 'use strict'
console.log(this)
}
func()
2.2作为对象方法被调用:指向调用对象
const food = {
name: '猪脚饭',
eat() {
'use strict'
console.log(this)
}
}
food.eat()
2.3箭头函数:指向定义时的作用域的this,没有自己的this,它的this是继承来的
改变this指:
调用时改变:用call、applay(以数组的方式传入参数)
创建时指定this:用bind(返回的是一个函数)、箭头函数