this的指向
普通函数
- 函数在调用时,js会默认给this一个值
- this的绑定和定义的位置没有关系
- this的绑定和调用方式以及调用位置有关系
- this是在运行时被绑定的
function test() {
console.log(this);
}
test();
const obj = {
name: 'obj',
test: test
}
obj.test();
test.apply(String('apply'));
test.call(String('call'));
test.bind(String('bind'))();
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22

内置函数的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>Documenttitle>
head>
<body>
<button>点击bu>
<script>
setTimeout(function () {
console.log('定时器函数:', this);
}, 0);
const btn = document.querySelector('button');
btn.onclick = function () {
console.log('btn的点击:', this);
}
var names = ['tom'];
names.forEach(function () {
console.log('forEach: ', this);
})
names.forEach(functio
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27