简体   繁体   English

有没有办法在 JavaScript 中命名箭头函数?

[英]Is there a way to name arrow functions in JavaScript?

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.对于普通的 JavaScript 函数,我可以只命名它们并从内部使用该名称。 For arrow functions, I'm currently using arguments.callee .对于箭头函数,我目前使用的是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);
    });
}

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.callee

arguments are not supported by arrow functions.箭头函数不支持arguments TypeScript currently incorrectly allows you to use them. TypeScript 当前错误地允许您使用它们。 This will be an error in the next version of TypeScript.这将是下一版 TypeScript 的错误。 This is to keep TypeScript arrow functions compatible with the JavaScript Language Specification .这是为了使 TypeScript 箭头函数与 JavaScript 语言规范兼容

For your use case I would just use a function .对于您的用例,我只会使用一个function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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