JavaScript 中 this的指向

本文深入探讨JavaScript中this关键字的复杂性和指向规则。解析在全局、对象方法、内嵌函数及不同作用域下this的具体指向,帮助开发者理解并正确使用this。

this 一方面便利了让大家在JS开发当, 但是另一方面让开发者头痛的是不清楚this 指代什么.

 

指向全局Window:

<script>
   console.log(this);
</script>

 

Function attached to global project. So "this" in the project will point to global project.

    <script>
        function calculateAge(year) {
            console.log(2018 - year);
            console.log(this);
        }
    </script>

 

在object的function中的innerFunction

一些开发者认为this 应该是指向object John, 因为还在John这个 object 的scope chain中.

JS Rules:

When a regular function code called, then the default object is the window object. This is how it happens in the browser.

InnerFunction is not a method, because the method is called calculateAge. Method of the John object.

InnerFunction although is written insdie of a method, it is still a regular function.

在网页中, 当一个普通的function 代码被call时, default object 是 window object.

InnerFunction 这样嵌套在method(John object里面的calculate function), 这样写在method里面的function, 是一个普通的function 而不是method, 所以this 指向全局window.

<script>
        var john = {
            name: 'John',
            yearOfBirth: 1990,
            calculateAge: function () {
                console.log(this);
                console.log(john.yearOfBirth);

                function innerFunction() {
                    console.log(this);
                }

                innerFunction();
            }
        }

        john.calculateAge();
    </script>

 

 

 

指向scope chain(作用域):

calculateAge 的function的"this"会指向当前scope chain作用域(john object)

this object refers to the object than called the method.

    <script>
        var john = {
            name: 'John',
            yearOfBirth: 1990,
            calculateAge: function() {
                console.log (this);
            }
        }

        john.calculateAge();
    </script>

 

 

更多this 原理:

http://www.ruanyifeng.com/blog/2018/06/javascript-this.html

转载于:https://www.cnblogs.com/TheMiao/p/9736697.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值