彻底搞懂this
普通函数的this
this的取值 不取决于函数的定义,而是取决于怎么调用的
-全局内调用:【fn()】指向window
-作为对象内的方法调用:【obj.fn()】 指向调用对象
-作为构造函数调用:【const ldh = new Star()】 指向实例对象
-特殊调用(call、apply、bind):【fun.call(obj)】 指向obj
-事件处理函数中调用:指向当前触发事件的DOM元素
-如果找不到所属的调用者:指向window
箭头函数中的this
箭头函数本身没有this,而是沿用上层作用域的this
箭头函数本身没有this,而是沿用上层函数作用域(非箭头函数)或者全局作用域的this
示例:
function foo(){
console.log(this)
}
foo() => window
foo.call({name:'张三'}) => {name:'张三'}
const obj = {
foo:function(){
console.log(this)
}
}
obj.foo.call({name:'张三'}) => {name:'张三'}
obj.foo()
const obj2 = {
foo:function(){
function bar(){
console.log(this)
}
bar()
}
}
obj2.foo()
function Star(name){
this.name = name
}
const ldh = new Star('刘德华') =>ldh
<div>按钮</div>
document.querySelector('div').addEventListener('click',function(){
console.log(this) =>div
})
const fn = () =>{
console.log(this)
}
fn.call({name:'张三'}) =>window
fn() =>window
document.querySelector('button').addEventListener('click', () => {
console.log(this) =>window
})
var name = '小王'
const user = {
name: '老王',
walk: () => {
console.log(this.name)
}
}
user.walk() => '小王'
const user = {
name: '小明',
sleep: function () {
const fn = () => {
console.log(this)
}
fn()
}
}
user.sleep() =>user
user.sleep.call(Window) =>window
const user = {
name: '小明',
sleep: function () {
const bar = () =>{
const fn = () => {
console.log(this)
}
fn()
}
bar()
}
}
user.sleep() => user
综合案例:
let length = 20;
let obj = {
length:100,
sayHi:function(){
console.log(this.length)
}
}
obj.sayHi() => 100
const fn = obj.sayHi
fn() => 0
const arr = [obj.sayHi,2,3]
const arr = [function(){console.log(this.length)},2,3]
obj.fn() === obj['fn']()
arr[0]() => 3