call方法的作用是调用函数并且改变函数的this指向,this指向为call方法的第一项,其余后面的都是参数。
apply() 与call()非常相似,不同之处在于提供参数的方式,apply()使用参数数组,而不是参数列表。

var Person = {
name: "zs",
age: 22,
};
function fn(x, y) {
console.log(x + "," + y);
console.log(this);
}
fn("hh", 20); //this指向的还是window
fn.call(Person,"hh",20) // this指向的是 Person

改变定时器中的this指向,我们有个更好的方法:bind

bind()创建的是一个新的函数(称为绑定函数),与被调用函数有相同的函数体,当目标函数被调用时this的值绑定到 bind()的第一个参数上

<!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 id="btn">按钮</button>
<div id="div1">div</div>
<script>


// var oDiv1 = document.getElementById("div1");
// oDiv1.onclick = function(){
// setTimeout(function(){
// console.log(this); //window对象
// },1000)
// }

var oDiv1 = document.getElementById("div1");
oDiv1.onclick = function(){
setTimeout(function(){
console.log(this); // 指向的是绑定事件的对象 <div id="div1">div</div>
}.bind(this),1000)
}
</script>
</body>
</html>