What does it mean equal and greater-than sign (=>) in Javascript? [duplicate]

删除回忆录丶 提交于 2020-01-03 20:02:00

问题


In Meteor Whatsapp example project is file where "=>" is used, but my WebStorm IDE detect it as error. I can't find any docs about this syntax.

chats.forEach( chat => {
  let message = Messages.findOne({ chatId: { $exists: false } });
  chat.lastMessage = message;
  let chatId = Chats.insert(chat);
  Messages.update(message._id, { $set: { chatId: chatId } })
});

GitHub repository for bootstrap.js file is here

What is "=>" ?


回答1:


I was actually about to downvote this question, but googling the answer proved surprisingly difficult if you don't already know what its called. As you can see in the links in the comments, that's a fat arrow function (sometimes referred to as just an arrow function).

There are some confusing aspects of arrow functions, so I'll hit some highlights:

Normal functions have a this pointer set depending on the context: functions called with new have it set to the newly-created object, functions called as methods have it bound to the object the method was called from, its otherwise bound to undefined or the global object (depending on the 'strict mode' pragma), and can of course be set with Function.prototype.bind et al.

But arrow functions have no binding for the this pointer created by the runtime (nor can it be specified via Function.prototype.bind), meaning it gets lexically looked up through scope chain resolution just like any other var. The MDN article is at best slightly confusing on this point (see link above).

Additionally, arrow functions have an implicit return, the return value will automatically be the last evaluated expression in the function body.

Arrow functions have no arguments psuedo-array. You can use ES 6 rest parameters instead.

For functions of arity 1, the parens around the parameter may be omitted.




回答2:


That's an es6 arrow function. If you switch to WebStorms settings:

you can switch your javascript version to ecmascript 6 like shown in the picture to make WebStorm recoginze them properly.




来源:https://stackoverflow.com/questions/33376028/what-does-it-mean-equal-and-greater-than-sign-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!