问题
I am studying JavaScript syntax. I occasionally see a pattern that confuses me: an equals sign on the right hand side of the arrow. For example, something like this:
.then(data => myVariable = data)
I don't know what is going on in that syntax. It looks like it is taking the value of data
and assigning it to the variable named myVariable
. Can somebody explain this?
回答1:
You're right. It's an arrow function (without an accompanying block) that "returns" an assignment expression - in effect doing an assignment of data
's value to myVariable
and returning the right hand side, though that might not be utilized in this case.
In a more simplified case:
let foo = 3;
function foobar(callback) {
const result = callback(5); //call callback with 5 as argument
console.log(result); //5
}
foobar(five => foo = five); //assigns 5 to foo
console.log(foo); //5
This is generally not the most readable option and your question proves this. I would recommend adding a block like so (if you don't intend on actually returning the right hand side value):
myPromise.then(data => {
myVariable = data;
});
In which case there is no implicit return of the assignment expression's right hand side and makes the intent clearer. Also, assignments such as what you're doing right with what I assume to an asynchronous promise are not encouraged.
Maybe look into async/await or other new ES features to deal with asynchronous code other than using variable assignments which may run into some problems if not used correctly.
回答2:
This is called fat arrow function in ES 6 . It is used for many purposes like
1.Arguments
If we want to pass and argument to a function.
Old Syntax :
let sum = function(x,y){
return x+y;
}
New Syntax with fat arrow
let sum = (x,y) => x+y;
//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
return {
id: id,
name: name
};
};
// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });
console.log(setNameIdsEs6 (4, "Kyle")); // Object {id: 4, name: "Kyle"}
Note : Return statement is not required in fat arrow of it is only one line .
2. Anonymous Function.
// ES5
API.prototype.get = function(resource) {
var self = this;
return new Promise(function(resolve, reject) {
http.get(self.uri + resource, function(data) {
resolve(data);
});
});
};
Using an arrow function, the same result can be achieved more concisely and clearly:
// ES6
API.prototype.get = function(resource) {
return new Promise((resolve, reject) => {
http.get(this.uri + resource, function(data) {
resolve(data);
});
});
};
来源:https://stackoverflow.com/questions/50184808/javascript-arrow-syntax-what-does-the-equals-sign-on-the-right-hand-side-mean