问题
I'm using arrow functions in an app and sometimes there is the need to get a reference to the function itself. For normal javascript functions, I can just name them and use the name from within. For arrow functions, I'm currently using arguments.callee
. Is there a way to name arrow functions so that a reference can be used from within?
Sample code
//typescript
private evaluateIf(expr: parserModule.IIfExpression, callback: IEnvCallback) {
this.evaluate(expr.condition, proceed=> {
guard(arguments.callee, arguments, this);
if (proceed !== false) this.evaluate(expr.then, callback);
else if (expr.else) this.evaluate(expr.else, callback);
else callback(false);
});
}
//javascript
Environment.prototype.evaluateIf = function (expr, callback) {
var _this = this;
this.evaluate(expr.condition, function (proceed) {
guard(arguments.callee, arguments, _this);
if (proceed !== false)
_this.evaluate(expr.then, callback);
else if (expr.else)
_this.evaluate(expr.else, callback);
else
callback(false);
});
};
What I settled on after the assistance since arguments might not be there forever
private evaluateIf(expr: parserModule.IIfExpression, callback: IEnvCallback) {
var fn;
this.evaluate(expr.condition, fn = proceed=> {
guard(fn, [proceed], this);
if (proceed !== false) this.evaluate(expr.then, callback);
else if (expr.else) this.evaluate(expr.else, callback);
else callback(false);
});
}
回答1:
Is there a way to name arrow functions so that a reference can be used from within
Not unless you assign it to a variable. For example:
var foo = () => {
console.log(foo);
}
For arrow functions, I'm currently using arguments.callee
arguments
are not supported by arrow functions. TS currently incorrectly allows you to use them. This will be an error in the next version of typescript. This is to keep typescript arrow functions compatible with the JS Language Specification.
For your use case I would just use a function
来源:https://stackoverflow.com/questions/29268866/is-there-a-way-to-name-arrow-functions-in-javascript