js中this的问题

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

——这是我的第一篇文章,如有错误,请见谅,并指出!

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值