return语句在JavaScript中不起作用
我的角度代码在按以下方式编写时不起作用:return语句在JavaScript中不起作用,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我的角度代码在按以下方式编写时不起作用: 这是: app.directive("strength", function() { return { require: "superhero", link: function(scope, element, attrs, superheroCtrl) { superheroCtrl.addStrength(); } } }) 但是,当return对象的第一个花括号与return语句位于同一行时,代码会起作
这是:
app.directive("strength", function() {
return
{
require: "superhero",
link: function(scope, element, attrs, superheroCtrl) {
superheroCtrl.addStrength();
}
}
})
但是,当return对象的第一个花括号与return语句位于同一行时,代码会起作用:
以下是有效的代码。
我做了其他不正确的事情吗?还有什么办法解决这个问题呢?
谢谢 这与语法有关。在第一种情况下,它会在
return
语句之后立即导致,而使用key/value定义对象文字的第二种语句只会成为语法错误,除非将其指定给
因此,您的声明相当于:-
return; //<-- Statement terminated here
{
require: "superhero", //<-- this will be a syntax error
link: function(scope, element, attrs, superheroCtrl) {
superheroCtrl.addStrength();
}
};
返回//您是否已将javascript文件添加到页面中?是的。JS文件位于html中的标记之间,我还添加了@PSL。因此答案是:如果同一行没有其他内容,则返回语句后会自动插入分号。@raneshu yes更准确地说返回语句受自动分号插入(ASI)的影响。return关键字和允许的表达式之间没有行终止符。
return; //<-- Statement terminated here
{
require: "superhero", //<-- this will be a syntax error
link: function(scope, element, attrs, superheroCtrl) {
superheroCtrl.addStrength();
}
};