JS 关于this对象

首先:在函数中this 到底取何值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不了。
(this 对象是在运行时基于函数的执行环境绑定的)

1.构造函数
如果函数作为构造函数用,那么它里面的 this 就代表它将要 new 出来的的对象

function A(){
    this.name="xiaoming";
    this.age="7";

    console.log(this);  //结果:A {name: "xiaoming", age: "7"}
}
 var a=new A();
 console.log(a.name);  //结果:xiaoming

如果我们直接调用A函数,而不是 new A(),结果就不一样了。(此时 this 就是 window)

function A(){
    this.name="xiaoming";
    this.age="7";

    console.log(this);  //结果:Window {postMessage: ƒ, blur: ƒ, focus: ƒ,....}
}
 A();  //注意!!!

2.函数作为一个对象的属性
函数作为一个对象的属性,并作为一个对象的属性被调用,该函数中的 this 指向该对象

var obj={
    x:10,
    fn:function(){
        console.log(this);  //结果:{x: 10, fn: ƒ}
        console.log(this.x);  //结果:10
    }
};
obj.fn();

注意:该函数必须作为一个对象的属性被调用,如下将函数赋到一个变量中并调用,此时this 值为 window

var obj={
    x:10,
    fn:function(){
        console.log(this);  //结果:Window {postMessage: ƒ, blur: ƒ, focus: ƒ,....}
        console.log(this.x);  //undefined
    }
};
var fn1=obj.fn;
fn1();

还有一种情况也为 (this =window)必须注意一下:

var obj={
    x:10,
    fn:function(){

           function f(){
            console.log(this);  //结果:Window {postMessage: ƒ, blur: ƒ, focus: ƒ,....}
            console.log(this.x);  //undefined
           }
           f();
    }
};
obj.fn();

3.函数用call 或 apply
一个函数用call 或 apply调用时,this 的值取传入对象的值

var obj={
    x:10,
};

var fn=function(){
    console.log(this);  //结果:{x: 10}
    console.log(this.x);  //结果:10
};
fn.call(obj);  //使用call 相当于  this=obj;

4.全局 / 调用普通函数
全局环境下,this 永远为 window!

    console.log(this===window) //结果:true
var fn=function(){
    console.log(this);  //结果:Window {postMessage: ƒ, blur: ƒ, focus: ƒ,....}
    console.log(this.x);  //结果:undefined
}
fn();

其实总的来说:

在全局环境中 this 等于 window
当函数被作为某个对象的方法调用时,this 就代表那个对象

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值