// this可以存储在任意位置,在不同位置代表不同对象.this表示执行函数时函数的拥有者.
// this在全局下表示window
// 普通函数中this表示window
// 事件处理函数中this表示触发事件的元素
// 在对象的方法中this表示对象本身
// 在定时器中this表示window
console.log(this); // window
function fun () {
console.log(this);
}
fun(); // window
document.onclick = fun; // document
var obj = {
name: 'lilei',
sayhi: fun
}
obj.sayhi(); // obj
setInterval(fun, 1000); // window
// this在不同位置表示不同对象, 可以使用call和apply修改this指向.
function fun() {
console.log(this);
}
fun(); // window
var obj = { name: 'lilei', age: 18 };
// 1.执行函数 2.修改函数内部的this指向
fun.call(obj); // obj
fun.apply(obj); // obj
function sum(a, b) {
console.log(this);
console.log(a + b);
}
// 如果有参数, call直接罗列参数, apply需要把参数放进数组中
sum(1, 2); // window 3
sum.call(obj, 1, 2); // obj 3
sum.apply(obj, [1, 2]); // obj 3
sum.call(1, 2); // Numer{1} NaN
sum.apply([1, 2]); // [1, 2] NaN
console.log(Math.max(1, 2, 3, 9, 8, 7)); // 9
var arr = [1, 2, 3, 9, 8, 7];
console.log(Math.max(arr)); // NaN
console.log(Math.max.apply(this, arr)); // 9
</script>