• 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

  • 相关阅读:
    Java批量文件打包下载
    Java Swing
    空白文章
    linux 用户创建、管理、权限分配
    在虚拟机下安装hadoop集成环境(centos7+hadoop-2.6.4+jdk-7u79)
    《转载》POI导出excel日期格式
    java导出生成word(类似简历导出)
    《sqoop实现hdfs中的数据导出至mysql数据库》
    c# winform 自动关闭messagebox 模拟回车
    Ubuntu下启动/重启/停止apache服务器
  • 原文地址:https://www.cnblogs.com/TheMiao/p/9736697.html
Copyright © 2020-2023  润新知