JavaScript - this关键字

this是 JavaScript 的一个关键字。在函数运行时,生成的一个内部对象,只能在函数内部使用,随着场景的不同,this也会发生变化。
总结一句话:this 就是指向调用函数的那个对象

四种场景:

1.单纯的函数调用
Code:

function one(){
    this.x = 10;
   console.info(this.x);
}
one();
console.info(x)

this代指window

2.作为对象方法调用

var stu = {
    name:'admin',
    age:20,
    getStuInfos:function(){
        //console.info(name+": "+age);
        console.info(this.name+": "+this.age);
    }
}
stu.getStuInfos();

this指的是stu对象

3.作为构造函数调用(this指向创建的对象)

function constr(){
    this.m = 10;
}
var newObj = new constr();
console.info(newObj.m);

this指向newObj

4.Apply调用

var name = 'admin-g';
var age = 30;
var stu = {
    name:'admin',
    age:20,
    getStuInfos:function(){
        console.info(this.name+": "+this.age);
    }
}
stu.getStuInfos.apply();//admin-g : 30  --不指定参数,this表示全局

this指的stu,但是由于apply,this还是指向window

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值