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这个对象。

原文地址:https://www.cnblogs.com/wuqiuxue/p/8351813.html