javascript中的this

1、在对象的方法中如果有this,那么该对象调用此方法时,this表示这个对象:

var obj1 = {attr:"a Obj",
aboutMe:function(){
    console.log(this.attr);
    }
     }

在控制台中实验:

这里写图片描述

该方法被赋值给其他变量时,this指向全局变量:
var obj2 = {
attr:”a Obj”,
aboutMe:function(){
if(this.attr) console.log(“still have thie attribute ‘attr’!”);
if(this === window)
console.log(“equal to window!!!”)
}
}

这里写图片描述

这里写图片描述
2、构造函数中的this指向构造的实例:
要有new 关键字!!!

var test = function(){
console.log(this);
};
test(); //window
new test(); // test()

这里写图片描述

一段比较绕的代码:

var test2 = function(){
 console.log(this);
 return function(){
 console.log(this);
 }
 };

测试:
在控制台中测试test2();、test2()();new test2();
注:图中的红色数字表示第几个console.log的输出
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值