javascript-BOM-this指向和js执行机制
this 指向问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button>点击</button>
<script>
// this 指向问题 一般情况下this的最终指向的是那个调用它的对象
// 1. 全局作用域或者普通函数中this指向全局对象window( 注意定时器里面的this指向window)
console.log(this);
function fn() {
console.log(this);
}
window.fn();
window.setTimeout(function() {
console.log(this);
}, 1000);
// 2. 方法调用中谁调用this指向谁
var o = {
sayHi: function() {
console.log(this); // this指向的是 o 这个对象
}
}
o.sayHi();
var btn = document.querySelector('button');
// btn.onclick = function() {
// console.log(this); // this指向的是btn这个按钮对象
// }
btn.addEventListener('click', function() {
console.log(this); // this指向的是btn这个按钮对象
})
// 3. 构造函数中this指向构造函数的实例
function Fun() {
console.log(this); // this 指向的是fun 实例对象
}
var fun = new Fun();
</script>
</body>
</html>
js执行机制
简单理解就是异步任务在同步任务后面,所以这段代码结果是:1 2 3
console.log(1);
setTimeout(function() {
console.log(3);
}, 1000);
console.log(2);
console.log(1);
setTimeout(function() {
console.log(3);
}, 0);
console.log(2);
//结果还是123
最后说一下异步任务,在任务队列时候,同一时间执行完成的,返回执行栈的顺序是一样的,但是在任务队列,不同时间完成的,那么速度快的则优先插入到执行栈,意思就是说,在应急车道上,如果是同一时间进入主车道的,那么就按照车的分类排队,如果在应急车道上,不同时间进入主车道的,那么哪辆车快,不管这辆车是什么分类,它都优先进入主车道第一的位置。
所以下面这段代码:同步任务第一优先显示,那么在异步任务的倒计时方法和时间方法,谁的执行完速度快,则优先输出结果。
<script>
console.log(1);
document.onclick = function() {
console.log('click');
}
console.log(2);
setTimeout(function() {
console.log(3)
}, 3000)
//同步任务放到最前面结果是:1 2
//
</script>