Hi I am just beginning with Angular, coming across one error,while just writing a simple skeleton program
let mod1 = function()
{
let task1 = function()
{
console.log('task one executed');
};
let task2 = function()
{
console.log('tasl 2 executed')
};
return
{
t1: task1,
t2: task2 //error here
};
};
let newmod = new mod1();
newmod.t1();
newmod.t2();
I am coming across an error of:
'Uncaught SyntaxError: Unexpected token :' in the //commented in front of line
Automatically a ;
is set after the return
. After it JS Compiler thinks that you have a scope
{
t1: task1,
t2: task2
};
And in this scope :
throws an error. So it is just an scope not an object with properties initializations.
Replace
return
{
t1: task1,
t2: task2 //error here
};
with
return {
t1: task1,
t2: task2
};
Cause
{ }
is not an object as one might think, but rather a block statement , commonly known in cases like:
if(true) { } // a block statement
while(true) { } // a block statement
So javascript expects it to contain statement, not key value pairs.
return
{
alert("works");
}
But why does the compiler does not interpret it as an object? Well, thats because its not part of an expression, just remove the newline, so that it becomes part of the returned expression:
return { /* object */ }
TLDR: never ever start an expression in a newline
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.