this

function test1() {
      console.log(this);
    }
    test1(); //window


    function test2() {
      'use strict';
      console.log(this);
    }
    test2(); //严格模式,this为undefined


    var obj1 = {
      name: 'zhouy2',
      sayName: function(){
        setTimeout(function(){
          console.dir(this);
          console.log(this.name);
        },1000);
      }
    }
    obj1.sayName(); //this指向window,name为空字符串


    var obj2 = {
      name: 'zhouy2',
      sayName: function(){
        setTimeout(function(){
          console.dir(this);
          console.log(this.name);
        }.bind(this),1000);
      }
    }
    obj2.sayName(); //由于有bind,this指向调用者


    var obj3 = {
      name: 'zhouy2',
      sayName: function() {
        setTimeout(() => {
          console.dir(this);
          console.log(this.name);
        },1000);
      }
    }
    obj3.sayName(); //箭头函数,this继承自obj,指向的是定义它的对象obj,而不是window


    window.val = 1;
    var obj = {
      val: 2,
      dbl: function() {
        console.dir(this)
        val *= 2;
        this.val *= 2;


        console.log(val);
        console.log(this.val);
      }
    }
    //有前缀,this指向obj
    obj.dbl(); //2 4
    var func = obj.dbl;
    //没有前缀,等价于window.func(),this指向window
    func(); 




    //多层嵌套箭头函数
    var od1 = {
      say: function() {
        var f1 = () => {
          console.log(this); //this指向obj
          setTimeout(() => {
            console.log(this); //this指向obj
          },1000);
        }
        f1();
      }
    }
    od1.say();


    var od2 = {
      say: function() {
        var f1 = function() {
          console.log(this); //this指向window
          setTimeout(() => {
            console.log(this); //this指向window
          },1000);
        }
        f1();
      }
    }
    od2.say();


    var od3 = {
      say: function() {
        'use strict';
        var f1 = function() {
          console.log(this); //this指向window
          setTimeout(() => {
            console.log(this); //this指向window
          },1000);
        }
        f1();
      }
    }
    od3.say();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值