Javascript中this是怎么工作的?

本文深入探讨JavaScript中this关键字的不同绑定方式及其应用场景,包括对象方法调用、函数调用、构造函数调用及apply或call调用等。通过具体示例说明this在不同上下文中如何被正确绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.作为对象方法调用
   var point={
           x:0,
           y:0,
           move:function(x,y){
               this.x=x;
               this.y=y;
           }
       }
       point.move(1,1);//this被绑定到当前对象,即point 对象
this在函数执行时去获取对应的值,而不是在函数定义时。
eg:
        var a = {
            aa: 0,
            bb: 0,
            fun: function(x, y) {
                this.aa = this.aa + x;
                this.bb = this.bb + y;
            }
        };
        var aa = 1;
        var b = {
            aa: 0,
            bb: 0,
            fun: function() {
                return this.aa;
            }
        };
        a.fun(3, 2);
        console.log(a.aa); //3 this指向对象本身
        console.log(b.fun()); //0  this指向对象本身
        (function(aa) {
            var c = aa();
            console.log(c);
        })(b.fun); //1  //由于fun在该处执行,导致this不再指向对象本身,而是window

2.函数调用
var x = 1;
        function test() {
            this.x = 0;
        }
        test();
        console.log(x);//0 函数调用 this被绑定到全局对象上。

缺点:内部函数的this也绑定全局对象,而我们希望这里的this绑定到其外层函数对应的对象上
解决方法:将this保存在一个变量中,再运用该变量即可
   var point = {
            x: 0,
            y: 0,
            moveTo: function(x, y) {
                var that = this;
                console.log(that);
                var moveX = function(x) {
                    that.x = x;

                };
                var moveY = function(y) {
                    that.y = y;
                }
                moveX(x);
                moveY(y);
            }
        };
        point.moveTo(1, 1);
        console.log(point.x);//1
3.构造函数调用。
this会绑定到新创建的对象上,避免了this绑定到全局对象上。

     var x = 2;

        function test() {
            this.x = 1;
        };
        var a = new test();
        console.log(x);//2
        console.log(a.x);//1

4.使用apply或call调用this将会被现实设置为函数调用的第一个参数
apply与call的区别在于一个要求传入的参数为数组,一个要求分别传入。
以apply为例
 var name = "window";
        var aa = {
            name: "Bob",
            showName: function() {
                return this.name;
            }
        };
        var other = {
            name: 'Jack'
        }
        console.log(aa.showName()); //'Bob' this对象绑定到当前对象
        console.log(aa.showName.apply()); //'window' apply()无参数时,this对象绑定到全局对象 
        console.log(aa.showName.apply(other)); //'Jack' 有参数时,this指向参数指定的对象


;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值