js this 指针的几种情况

牵扯到js函数调用,this指针就不可避免的要涉及,那么this指针到底指向谁,请牢记:“this永远指向当前正在执行的函数对象”,js函数有四种情况,分别是:

  1. 当函数是函数声明或者函数表达式时
  2. 当函数是对象的方法时
  3. 当函数是构造函数时
  4. 当函数是通过函数方法调用时

NO1:

<script type="text/javascript">
            function test1 (a,b) {
                console.log(this);//this=>window
                return document.write(a*b+"<br />");
            }
            test1(2,5);//返回10
            
            var test2 = function (a,b) {
                console.log(this);//this=>window
                return document.write(a*b);
            }
            test2(2,5)//返回10
        </script>

解释说明:针对这种情况,函数本身就是全局对象,而在html中全局对象就是html本身,而在浏览器中页面对象就是浏览器窗口对象(window),所以以上函数会自动成为window对象下的函数

NO2:

var objFun = {
                a:2,
                b:8,
                test3:function (a,b) {
                    console.log(this);//this=>object本身
                    return document.write(a*b+"<br />");
                    //return document.write(this.a*this.b+"<br />");
                }
            }
            objFun.test3(2,5);//返回10

解释说明:test3是一个函数(也是objFun的一个方法),函数本身归属于对象(这是因为函数的typeof为function,而function本身就是对象),而objFun是函数的所有者,所以this指向objFun本身

NO3:

function test4 (a,b) {
                this.first = a;
                this.second = b;
                console.log(this);//this=>test4本身
            }
            var x = new test4(2,5);

解释说明:这里使用了new关键字,而new关键字的作用就是重新建立一个对象,所以this指向test4本身,

大家也可以试着在控制台打印出他们的typeof结果看一下。

转载请注明出处!=>http://www.cnblogs.com/zxn-9588/p/8916152.html 

原文地址:https://www.cnblogs.com/zxn-9588/p/8916152.html