相关疑难解决方法(0)

箭头函数与函数声明/表达式:它们是等效/可交换的吗?

规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.

ES2015中的箭头功能提供了更简洁的语法.我现在可以用箭头功能替换所有函数声明/表达式吗?我需要注意什么?

例子:

构造函数

function User(name) {
  this.name = name;
}

// vs

const User = name => {
  this.name = name;
};
Run Code Online (Sandbox Code Playgroud)

原型方法

User.prototype.getName = function() {
  return this.name;
};

// vs

User.prototype.getName = () => this.name;
Run Code Online (Sandbox Code Playgroud)

对象(文字)方法

const obj = {
  getName: function() {
    // ...
  }
};

// vs

const obj = {
  getName: () => {
    // ...
  }
};
Run Code Online (Sandbox Code Playgroud)

回调

setTimeout(function() {
  // ...
}, 500);

// vs

setTimeout(() => {
  // ...
}, …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 arrow-functions

449
推荐指数
2
解决办法
12万
查看次数

箭头功能和此

我正在尝试ES6,并希望在我的函数中包含一个属性,就像这样

var person = {
  name: "jason",

  shout: () => console.log("my name is ", this.name)
}

person.shout() // Should print out my name is jason
Run Code Online (Sandbox Code Playgroud)

但是,当我运行此代码控制台时只记录日志my name is.我究竟做错了什么?

javascript this ecmascript-6 arrow-functions

19
推荐指数
3
解决办法
8492
查看次数

标签 统计

arrow-functions ×2

ecmascript-6 ×2

javascript ×2

this ×1