美文网首页
箭头函数的使用注意事项

箭头函数的使用注意事项

作者: Zzzz_e02b | 来源:发表于2019-11-18 08:30 被阅读0次

箭头函数的使用注意事项

js中this的使用一直以来都比较难以理解,和php相比要复杂许多。自从ES6中新增了箭头函数的API,this的使用情况变得更加复杂。这里做几点简单的对比~
主要资料参考自大神阮一峰翻译的:阮一峰ES6教程

1, 箭头函数没有prototype(原型),所以箭头函数本身没有this,也就不能用call()、apply()、bind()这些方法去改变this的指向。
let a = () => {}; 
console.log(a.prototype); // undefined
2, 箭头函数的this指向在定义的时候继承自外层第一个普通函数的this。如果箭头函数外层没有普通函数,它的this会指向window(全局对象)
function test() {
  this.type = 'cat'
  this.obj = {
    name: 'tom',
    getType: () => {
      return this.name + ',' + this.type
    },
    getName: function () {
      return this.name + ',' + this.type
    }
  }
}
let t = new test()
console.log(t.obj.getType())
console.log(t.obj.getName())
// "undefined,cat"
// "tom,undefined"

值得注意的是:如果外层的普通函数的this指向发生改变,箭头函数的this跟着会发生改变。

3,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

var id = 21;

foo.call({ id: 42 });
// id: 42

本例通过call()方法替换了foo()的上下文context,使foo的this指向了新的对象。由于setTimeout 的参数为一个箭头参数,它的生效时间是在100毫秒之后,箭头函数输出了42

4, 箭头函数没有constructor,使用new调用箭头函数都会报错
let a = () => {};
let b = new  a(); // a is not a constructor

同是也无法使用new.target
更多移步:阮一峰ES6教程 -- new-target-属性

5, 箭头函数的arguments

第一种情况:箭头函数的this指向全局对象,会报arguments未声明的错误。
第二种情况是:箭头函数的this如果指向普通函数,它的argumens继承于该普通函数。

let foo = () => {
  console.log(arguments);
};
foo(1, 2, 3, 4); // Uncaught ReferenceError: arguments is not defined
function foo() {
  setTimeout(() => {
    console.log('args:', arguments);
  }, 100);
}

foo(2, 4, 6, 8)
// args: [2, 4, 6, 8]

可以使用rest参数(扩展运算符...)来获取函数的不定数量参数

let foo = (first, ...rest) => {
  console.log(first,  rest) // 1 [2, 3, 4]
};
foo(1, 2, 3, 4)
6,不可以使用yield命令,因此箭头函数不能用作 Generator 函数。

相关文章

  • ES6函数

    箭头函数的声明 ES6 箭头函数声明注意事项: 如果箭头函数不需要参数 或者 需要多个参数,就要使用圆括号代表参数...

  • VUE 学习笔记

    新建项目 注意事项 methods、watch、生命周期,不能使用箭头函数(箭头函数的 this 绑定父级上下文,...

  • 箭头函数中的this

    1. 箭头函数(注意事项) 2.其中this也有注意事项: 3、其实就是一句话:箭头函数可以让setTimeout...

  • ES6箭头函数注意事项

    箭头函数使用注意事项:1、函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。 2、不可以当做构...

  • 箭头函数

    箭头函数 为什么使用箭头函数

  • 箭头函数的理解

    箭头函数的理解: ES6中新增的一个特性:=> 箭头函数的一些注意事项: 箭头函数中的this是函数定义时所在的对...

  • ECMAScript 6 箭头函数

    箭头函数 ES6 允许使用“箭头”(=>)定义函数。 使用注意点 箭头函数有几个使用注意点。 (1)函数体内的th...

  • Es6知识点总结

    methods 不能使用箭头函数 为啥?在箭头函数中使用this的话指向的是组件本身 如果不使用箭头函数 this...

  • 箭头函数的使用注意事项

    箭头函数的使用注意事项 js中this的使用一直以来都比较难以理解,和php相比要复杂许多。自从ES6中新增了箭头...

  • 箭头函数和数组

    箭头函数&数组 箭头函数 特点: 没有 this 没有 arguments 没有prototype在箭头函数中使用...

网友评论

      本文标题:箭头函数的使用注意事项

      本文链接:https://www.haomeiwen.com/subject/vitvictx.html