es6中的this关键字与箭头函数

首先js中的函数调用有三种形式

func(p1, p2) 
obj.child.method(p1, p2)
func.call(context, p1, p2) 

前面两种都是语法糖,可以等价地变为 call 形式。

func(p1, p2) 等价于
func.call(undefined, p1, p2)

obj.child.method(p1, p2) 等价于
obj.child.method.call(obj.child, p1, p2)

而this指向的便是函数中的context即上下文,或函数当前运行环境。
当我们在浏览器控制台中写下下面的函数:

function func(){
  console.log(this)
}

func()

其等价于

func.call(undefined)

在浏览器中undefined默认的context为window对象。
在这里插入图片描述
如果将代码改为:

function func(){
  console.log(this)
}

func.call({id:1})

则结果变为
在这里插入图片描述
这是因为函数当前运行的环境由undefined变为了{id:1}这个对象。
举几个例子:

function Cat(){
  name: 'kitty',
  print: function(s=''){console.log(s+this.name)},  // context是类为Cat的对象
  init: function() {
    button.addEventListener('click',
      function(){this.print('init ')};
  }  // context是button 
}

setInterval(function(){console.log(this),1000) // context为全局对象window

箭头函数是es6加入的函数定义方式相当于其他语言中的匿名函数

var f = () => {console.log('hello!')}

等价于

function f(){console.log('hello!')}

箭头函数具有如下特点,也可以说是于普通函数定义的不同之处:

  1. 箭头函数没有自己的this。箭头函数的this是相同情况下function的上一级作用域的运行环境。
  2. 不同时也没有自己的arguments、super、new.target,这点和this一样。
  3. 因为没有this,所以不能当构造函数。
  4. 不可以使用yield命令,因此箭头函数不能用作 Generator 函数。

同样举几个例子:

function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // context为Timer
  setInterval(() => this.s1++, 1000);
  // context为window
  setInterval(function () {
    this.s2++;
  }, 1000);
}

普通函数的context为全局对象window,因为setInterval是全局对象window内的一个函数,而箭头函数没有自己的this,它的context需要通过在setInterval的上一级作用域中寻找,也就是Timer。

var handler = {
  id: '123456',

  init: function() {
    document.addEventListener('click',
      event => this.doSomething(event.type), false);  //context为handler
  },

  doSomething: function(type) {
    console.log('Handling ' + type  + ' for ' + this.id);
  }
};

同样的上述箭头函数换成普通函数则context为document。

function foo() {
  return () => {
    return () => {
      return () => {
        console.log('id:', this.id);
      };
    };
  };
}

var f = foo.call({id: 1});

var t1 = f.call({id: 2})()(); // id: 1
var t2 = f().call({id: 3})(); // id: 1
var t3 = f()().call({id: 4}); // id: 1

由于函数foo内返回的都是箭头函数,因此只有一个this,就是函数foo的this,在这里被call()定义为对象{id:1}

// ES6
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

// ES5
function foo() {
  var _this = this;

  setTimeout(function () {
    console.log('id:', _this.id);
  }, 100);
}

箭头函数的作用相当于在函数开头是声明var _this = this,将_this在函数foo中的值固定下来,以免后续this不断的变化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值