1. 普通函数this指向window
function demo(){
console.log(this)
}
demo()
2. 匿名函数this指向window
let fn=function(){}
3.立即执行函数this指向window
(function(){})()
4.回调函数this指向window
const message = function() {
console.log("This message is shown after 3 seconds");
}
setTimeout(message, 3000);
setInterval(message,1000)
5.箭头函数this指向函数定义位置的上下文this
var obj = { uname: "张三", age: 21 }
function fn() {
console.log(this,"外层函数")
return () => {
console.log(this,"箭头函数")
}
}
let result = fn.call(obj)
result()
6.对象下的函数谁调用this this就指向谁
var age=100;
var obj = {
age: 20,
say: () => {
alert(this.age)
}
}
obj.say()
7.dom回调 this指向绑定事件的对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>点击</button>
</body>
</html>
<script>
let button = document.querySelector("button")
button.onclick = function () {
console.log(this);
}
</script>
8总结
(1) this总是指向函数的直接调用者(而非间接调用者)
(2) 如果有new关键字,this指向new出来的那个对象
(3) 在事件中,this指向目标元素,特殊的是IE的attachEvent中的this总是指向全局对象window。
二.改变this指向
1.call()
通过call()方法可以改变this指向 并且立即执行
2.apply()
通过apply()方法可以改变this指向 参数放到一个数组里面 并且立即执行
3.bind()
通过bind()方法可以改变this指向 原函数不立即执行
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
/************改变this指向*
* call 立即执行
* apply 立即执行,参数放到一个数组里
* bind 不会立即执行
* *************/
function Demo(uname, age) {
// console.log(this)
console.log(uname, age)
}
//call bind apply
let obj = {}
// Demo.call(obj, "张三", 21) //改变this指向,并立即执行
// let f = Demo.bind(obj, "张三", 21) //改变this指向,不立即执行
// f() //执行新的函数
Demo.apply(obj, ["张三", 21]) //改变this指向,并立即执行;参数放到数组里
</script>
</head>
<body>
</body>
</html>