Javascript中this关键字

  • this 是谁调用的时候,指定的是谁,通俗一点讲就是,函数是谁执行是不是由其中一个对象点出来的那就是代表它,
  • 比如执行对象a中b函数a.b();这个b函数中this代表a;
  • 当换成var c=a.b; c(); 这样执行的话,b函数赋值给了一个变量c,这样直接执行c 函数的时候,this代表整个window;
  • 有个简易记法:看执行函数前面是否有对象,有对象点出来的函数执行时,this就是此对象;反之就是指window;
var obj = {
            x: 1,
            fu: function () {
                console.log("outer:"+this.x);
                console.log("outer:" + this);
                function f1() {
                    console.log("f1:" + this.x);
                    console.log("f1:" + this);
                }
                f1();
            }
        };
        obj.fu();
        //outer:1
        //outer:[object Object]
        //f1:undefined
        //f1:[object Window]
  • New 出来的函数this指代函数本身
function foo() {
       this.name = "乌梅";
       this.age = 26;
       console.log(this);
}
var a = new foo();//foo {name: "乌梅", age: 26}
原文地址:https://www.cnblogs.com/meiyh/p/6207671.html