function函数
1 默认指向
全局调用函数,函数体内的this指向window对象
num = 1
function testfunc(){
console.log(this)
console.log(this.num);
}
testfunc()
Window {window: Window, self: Window, document: document, name: "", location: Location, …}
this.html:14 1
严格模式下:this默认指向为undefined
num = 1
function testfunc(){
'use strict'
console.log(this)
console.log(this.num);
}
testfunc()
undefined
this.html:15 Uncaught TypeError: Cannot read property 'num' of undefined
at testfunc (this.html:15)
at this.html:17
testfunc @ this.html:15
(anonymous) @ this.html:17
2 隐式指向
当一个函数在一个对象内被调用时,函数体内的this指向这个对象
num = 1
function testfunc(){
console.log(this)
console.log(this.num);
}
let obj = {
num: 10,
func: testfunc
}
obj.func()
{num: 10, func: ƒ}
10
3 显示指向
使用call apply bind可以改变this的指向
num = 1
function testfunc(){
console.log(this)
console.log(this.num);
}
let obj = {
num: 10,
func: testfunc
}
let objA = {
num: 199
}
obj.func.call(objA)
{num: 199}
199
4 构造函数
function Persion(name){
this.name = name
this.hello = function(){
console.log(this)
console.log('hello'+this.name)
}
}
let p1 = new Persion('xiaobai')
p1.hello()
Persion {name: "xiaobai", hello: ƒ}hello: ƒ ()name: "xiaobai"__proto__: Object
this.html:15 helloxiaobai
箭头函数
一层一层找到最上层的函数调用
function fa(){
setInterval(t=>{console.log(this)},1000)
}
fa();
箭头函数中的this会一层一层向上找到最上层函数。