this的指向问题
- 使用对象调用函数时(函数为对象上的属性),谁调用this就指向谁
let obj = {
test:function(){
console.log(this)
},
arrowTest:()=>{},
test2:function(){
console.log(this)
function temp(){
console.log(this)
}
},
}
obj.test() // 指向obj {test: ƒ}
- 使用new 调用构造方法时,this为新创建的对象,原型链指向方法的prototype,constructor为调用的构造方法
new obj.test() //test {}
- 直接调用的函数,this指向window
//例一
let func1 = obj.test;
func1()// 指向window
// 例二
obj.test2();
// 第一个this 为obj
// 第二个this输出为 window
- call apply bind 可以改变this的指向,this为指定的对象,指定的对象为null时,this指向window
obj.test.call({})// 指向{}
obj.test.apply({})// 指向{}
let bindfunc = obj.test.bind({})
bindfunc()// 指向{}
如果指定的对象为null 或者 undefined 或者不传,则this指向window
obj.test.call()// 指向window
obj.test.apply()// 指向window
let bindfunc = obj.test.bind()
bindfunc()// 指向window
obj.test.call(null)// 指向window
obj.test.apply(null)// 指向window
let bindfunc = obj.test.bind(null)
bindfunc()// 指向window
obj.test.call(undefined)// 指向window
obj.test.apply(undefined)// 指向window
let bindfunc = obj.test.bind(undefined)
bindfunc()// 指向window
如果指定对象为基本类型,会在绑定时调用基本类型的构造方法,构造出一个基本类型对象
obj.test.call(1)// 指向Number {1}
obj.test.apply(1)// 指向Number {1}
let bindfunc = obj.test.bind(1)
bindfunc()// 指向Number {1}
- 箭头函数的this指向声明箭头函数的作用域,不是谁调用指向谁。
箭头函数没有arguments this new.target 它的这些参数指向定义时作用域的arguments this new.target,如果定义的环境没有arguments new.target,使用arguments new.target会报错
箭头函数没有原型
使用场景:匿名函数(事件处理,异步方法),不想改变this指向,代码简洁性
obj.arrowTest()// 指向window
obj.test.arrowTest({})// 指向window
obj.test.arrowTest({})// 指向window
let bindfunc = obj.test.arrowTest({})
bindfunc()// 指向window
- dom事件的this指向监听的事件的dom元素
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no,maximum-scale=1">
<style>
#main{
height:400px;
}
</style>
</head>
<body>
<div id="main"><span>3423424242</span><br><span>3423424242</span><br><span>3423424242</span><br><span>3423424242</span><br><span>3423424242</span></div>
<script>
document.getElementById('main')
.addEventListener('click',
function(){
console.log(this)// this为document.getElementById('main')节点
})
</script>
</body>