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>
内置函数的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>点击</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