简体   繁体   中英

Understanding difference between following javascript notations

I am trying to learn js codes and was going through some sample codes at GitHub and was confused between these codes. What is the difference between following or they are same.I deleted the contents inside to keep it simple.

on_success: (file_doc) => {
}


on_success(file_doc) {
}

The first notation can be used only in object literals , and assigns an anonymous arrow function to the object's property on_success . In contrast to a non-arrow function, this preserves the outer this ; so this inside the function will point to whatever it pointed to at the moment of assignment.

Example:

const obj = {
  on_success: (file_doc) => {},
}

obj.on_success();

The second notation can only be used in Javascript classes , and defines a named non-arrow-function on each instance of the class. Non-arrow (also known as ES5-function ) means this inside it will reference whatever the execution context of the function is.

Example:

class Foo {
  on_success(file_doc) {}
}

const bar = new Foo;
bar.on_success();

It's same as:

const success = (file_doc) => {

}

function success(file_doc) {

}

The first one called arrow syntax function or method introduced in ES6 and the second one is from ES5 (correct me if I'm wrong)

They're the same as a function or method but the arrow syntax function doesn't have this and arguments variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM