js中的this问题
一. 根据函数的调用方式不同,this会指向不同的对象
1.以函数的形式调用时,this指向window对象(严格模式下为 undefined)
2.以方法的形式调用时,this指向调用该方法的对象
3.当以构造函数的形式调用时,this指向新创建的那个对象
4.使用call()和apply()调用时,this指向()内指定的那个对象
二. 箭头函数
this是静态的,this始终指向函数声明时所在作用域下的this的值
let ad=document.getElementById("ad");
ad.onclick=function(){
//这里this指向 ad
console.log(this);
}
ad.onclick=()=>{
//箭头函数的this指向的是window
console.log(this);
}
箭头函数适合 与this无关的回调,如定时器
ad.onclick=function(){
let _this=this;
//定时器
setTimeout(function(){
/*
此时的 this 指向 window ,window 没有style所以下面会报错
this.style.background="pink"; 错误
解决方法:将上一层的this赋值给一个新的变量_this
*/
_this.style.background="pink";
},2000);
ad.onclick=function(){
setTimeout(()=>{
//箭头函数的this就是此函数所在作用域下的this ad
this.style.background="pink";
},2000);
}
闭包问题中涉及到的this问题
http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html 阮一峰的学习 js 的闭包文章后面的思考题
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
//这里this 指向的是window对象
return this.name;
};
}
};
console.log(object.getNameFunc()());//The Window
/*
let f1=object.getNameFunc();
let result=f1();这是在全局环境下调用的函数 所以this指向window
*/
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
//that是函数内部的变量 此时的this指向object
var that = this;
return function(){
//闭包可访问函数内部的变量
return that.name;
};
}
};
console.log(object.getNameFunc()());//My Object
——这是我的第一篇文章,如有错误,请见谅,并指出!