[[toc]]
普通函数this指向什么?
普通函数的this指向哪里?
- this指向调用它的对象
- 函数定义无法确定,只有函数执行时才能确定
普通函数有哪些?
- 没有调用者的函数
- 对象内函数
- 使用apply
// 没有调用者的函数: this(非严格)指向全局window
function test(){console.log('this=',this) // this=window
}
test()
// 对象内函数: 只有1层,this指向调用者对象
const school = { name: 'abc',course(){console.log('this=',this) // this= schoolconsole.log('name=',this.name) // name=abc}
}
school.course()
// 对象内函数: 有多层对象,this指向最近调用者对象
const outer = { name: 'outer',inner:{name: 'inner',fn(){console.log('this=',this) // this= innerconsole.log('name=',this.name) // name=inner}}
}
outer.inner.fn()
// 使用apply: 方法fun内部的this为apply参数1,如果参数1为null,则默认全局对象
const obj1 = {name: '对象1'}
function fn(a){console.log</