1. 程式人生 > >JavaScript 中 this的指向

JavaScript 中 this的指向

UNC lar -c when ack regular poi ole die

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>

JavaScript 中 this的指向