首页 > 解决方案 > 由于缩进,Angular 1 中出现错误

问题描述

我是 Angular JS 的新手,正在努力学习。尝试编写一个提供程序,它的行为方式很奇怪并引发错误。您能否帮助确定错误的原因。

这是运行良好的代码:

myapp.provider('Testing',function(){    
return {
    $get: function() {
        return          {
            add: function(a,b){return a+b;}
        };
    }
};
});

以下是无法正常工作的代码:

myapp.provider('Testing',function(){    
return {
    $get: function() {
        return          
        {
            add: function(a,b){return a+b;}
        };
    }
};
});

由于第二个片段的错误:

未捕获的语法错误:意外的令牌(

错误指向这个语句:add: function(a,b){return a+b;}

两个代码片段的唯一区别是{$get 定义函数中返回语句的“”位置。

是否有任何正当理由说明“ {”的位置很重要。

标签: angularjs

解决方案


Yes, the placement of "{" after return matters. It is a default JavaScript behavior to close a statement automatically at the end of a line. So,

return          
        {
            add: function(a,b){return a+b;}
        };

The function will return undefined and the next parentheses will be act as Unexpected token

return ;       
            {
                add: function(a,b){return a+b;}
            };

推荐阅读