js箭头函数与普通函数的this指向问题
总结一句话 普通函数的this指向调用者,箭头函数的this指向拥有者。
例子:
js
// 常规函数:
hello = function() {
document.getElementById("demo").innerHTML += this;
}
// window 对象调用该函数:
window.addEventListener("load", hello);
// button 对象调用该函数:
document.getElementById("btn").addEventListener("click", hello);
输出: 普通函数this指向调用者,第一次是window调用,第二次是button调用。
js
[object Window] [object HTMLButtonElement]
js
// 箭头函数:
hello = () => {
document.getElementById("demo").innerHTML += this;
}
// window 对象调用该函数:
window.addEventListener("load", hello);
// button 对象调用该函数:
document.getElementById("btn").addEventListener("click", hello);
输出: 该例子里 箭头函数不论你调用者是谁,拥有者都是window。
js
[object Window] [object Window]