this指向
- 普通函数调用 window
- 定时器 window
- 立即执行函数 window
- 构造函数调用 实例对象
- 对象方法调用 该方法所属的对象
- 事件绑定方法 绑定事件对象
普通函数和箭头函数的区别
- 箭头函数this指向上一级
- 不能用作构造函数(不能使用new,否则会抛出错误)
- 不能使用argument对象
普通函数的this
非严格模式 this-->window
严格模式 this-->undefined
function fn(){
console.log(this)
} // window
'use strict'
function fn(){
console.log(this)
} // undefined
call apply bind 中的this
情况1: this--> window ( apply 和 call 同理)
a.call()
a.call(undefined)
a.call(null)
function a(){
console.log(this)
}
a.call() // window
a.call(undefined) // window
a.call(null) // window
情况2: 传什么 this指向什么
function a(){
console.log(this)
}
a.call({x:100}) // {x:100}
a.apply(123) // 123
const fn = a.bind({y:11})
fn() // {y:11}
// bind返回的是一个函数,需要一个函数接收 调用
**定时器中的this **
定时器 +function this--> window
定时器 + 箭头函数 this --> 上层作用域的this
// 练习一
var name = 'windowName'
var a = {
name : 'cherry',
fn:function(){
console.log(this.name);
}
}
a.fn()
// 指向调用者a,a的name为cherry
// 练习二
var name = 'windowName'
var a = {
name : 'cherry',
fn:function(){
console.log(this.name);
}
}
var f = a.fn
f()
// f()无调用者,默认指向window
// 练习三
var name = 'windowName'
function fn(){
var name = 'cherry'
console.log(this) // window
innerFun()
function innerFun(){
console.log(this.name);
}
}
fn()
// fn 无调用者 this-->window innerFun也无调用者
// 1、 cherry 2、 windowName 3、 windowName