this用于访问当前方法调用时所属的对象,函数的this和定义无关和调用有关
1、 直接调用如果是普通函数普通模式指向windows,对于严格模式指向undefined
function show() {
console.log("this 指向"+this)
}
show();
2、挂在对象上,然后执行方法——this为对象
document.onclick = function () {
console.log("this 指的是"+this)
}
3、定时器———this为window
setTimeout(function(){
console.log("this 指的是"+this)
},100)
4、构造函数new ———-当前构造函数的对象
function Show() {
console.log("this指得是"+this )
}
var show = new Show();
5、工具函数
this根据第一个参数决定
function Show() {
console.log("this指得是"+this )
}
Show.call(this)
Show.call(88)
其次foreach的第二个参数不写的话,this指向window
let arr = [1, 2, 3, 4]
arr.forEach(function(item){
console.log("this指的是" + this)
});
如果第二个参数写进去的话同call apply的用法
let arr = [1, 2, 3, 4]
arr.forEach(function(item) {
console.log("this指的是" + this)
},"name");