简体   繁体   English

为什么javascript不允许无分配的匿名函数?

[英]Why does javascript not allow an anonymous function with no assignment?

"Unexpected Token (" Thrown from line 1. Why ? “意外令牌(从第1行抛出。为什么?

function (a,b,c) {
        // code    
    } 

Techfoobar is essentially correct, another way to explain it is that a FunctionDeclaration must have a name, whereas in a FunctionExpression the name is optional. Techfoobar本质上是正确的,另一种解释方式是FunctionDeclaration必须具有名称,而在FunctionExpression中 ,名称是可选的。

What is the difference between the two? 两者有什么区别? A function declaration is any statement that starts with the reserved word function . 函数声明是任何以保留字function开头的语句 So: 所以:

function foo() {}

is a function declaration. 是一个函数声明。

A function expression is like a declaration but it appears anywhere in a statement other than the start , so: 函数表达式类似于声明,但是它出现在语句中除start之外的任何位置,因此:

(function (){});
var x = function(){};
if (6 != function(){return 'foo';}()){}

are all function expressions and do not need names. 都是函数表达式,不需要名称。

Because there is a syntax error. 因为存在语法错误。 Your function has no name. 您的函数没有名称。

Your function either has to have a name if it is to be defined the way you've done. 如果要按照您的操作方式定义函数,则必须具有一个名称。

To check this, paste your code in Firebug console and execute it. 要进行检查,请将代码粘贴到Firebug控制台中并执行。 You'll get the error 你会得到错误

SyntaxError: function statement requires a name SyntaxError:函数语句需要一个名称

You can correct it by giving your function a name. 您可以通过给函数命名来更正它。

For example: 例如:

function foo(blah) {
    ...
}

For anonymous functions defined in the global scope, you either need to assign it to something OR you need to immediately execute it. 对于在全局范围内定义的匿名函数,您要么需要将其分配给某个对象,要么需要立即执行它。

ie

either 要么

var x = function(blah) {
    ...
};

OR 要么

(function(blah) {
    ...
})(arguments);

because otherwise there is absolutely no way they can be called. 因为否则绝对不可能调用它们。

Missing name in function statement. 函数语句中缺少名称。 check it with jslint jslint检查

try 尝试

function tdip() {
    var ts = tdip.find('>span');
    var trap = [];
    ts.contents().each(

    function () {
        if ($(this).is(':visible')) {
            if (this.nodeType == 3 && this.data.length > 0) {
                trap.push(this.data.trim());
            } else if ($(this).text && $(this).text().length > 0) {
                trap.push($(this).text().trim());
            }
        }
    });
    return trap.join('');
}

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

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