JavaScript 中 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