zoukankan      html  css  js  c++  java
  • JS高级——函数的调用模式

    函数调用模式一共有四种

    <script>
        //1.函数模式
        //this指向window全局对象
    
        //2.方法模式
        //this指向调用这个方法的对象
    
        //3.构造函数模式
        //this 使用new创建出来的对象
        
        //上下文模式
    
        function test(){
            console.log(this);
        }
        test();//window
    
        var obj1 = {
            test:function(){
                console.log(this);
            }
        }
        obj1.test();//Object
    
        function Person(){
            console.log(this);
        }
        var obj =new Person();//Person
    </script>

    练习理解

    <script>
        var age = 38;
        var obj = {
            age: 18,
            getAge: function () {
                console.log(this.age);
            }
        };
    
        var a = obj.getAge();  //18
        var getAge = obj.getAge;
        getAge();//38
    
    </script>
    <script>
       var age = 38;
       var obj = {
           age: 18,
           getAge: function() {
    
               console.log(this.age);
    
               function foo() {
                   console.log(this.age);
               }
               foo();
           }
       };
       obj.getAge();//18  38
    </script>
    <script>
        var length = 10;
        function fn(){
            console.log(this.length);
        }
    
        var obj = {
            length: 5,
            method: function (fn) {
                fn();
                arguments[0]();
            }
        };
    
        obj.method(fn, 123, 456, 789);//10    4
    </script>

    arguments是一个伪数组,里面有参数,arguments[0],就相当于arguments.0(),这是方法调用模式,所以this指向了arguments这个对象。

  • 相关阅读:
    2020.9.26
    2020.10.2
    判断方法
    sql与include
    File类的获取方法
    【每日日报】第十五天
    【每日日报】第十三天
    【每日日报】第十四天
    两数相加(输入框)
    判断闰年
  • 原文地址:https://www.cnblogs.com/wuqiuxue/p/8351813.html
Copyright © 2011-2022 走看看