码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript 中 this的指向

时间:2018-10-02 17:26:55      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:use   die   call   win   UNC   because   ons   pre   不清楚   

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的指向

标签:use   die   call   win   UNC   because   ons   pre   不清楚   

原文地址:https://www.cnblogs.com/TheMiao/p/9736697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!