Declaring a local variable
I want to declare a local variable as such:
(var n=1)
Mostly so I can manipulate the order it gets evaluated in.
Eg Then I could do
var increaseadNumber = (
ar={
inc开发者_Go百科:function(n){
return n+1
},
dec:function(n){
return n+2
}
}
).inc(1);
console.log(ar)//the object
console.log(increaseadNumber )//2
But, in my example ar is in the global namespace, and
var increaseadNumber = (
var ar={
inc:function(n){
return n+1
},
dec:function(n){
return n+2
}
}
).inc(1);//syntax error
generates "SyntaxError: Unexpected token var"
Granted I could declare this over 2 statements, but I would prefer to it with 1 statement.
Why not separate it into two lines?
var ar={inc:function(n){return n+1},dec:function(n){return n+2}};
ar.inc(1);
And add some sensible white space while you're at it:
var ar = {
inc: function(n) {
return n + 1
},
dec: function(n) {
return n + 2
}
};
ar.inc(1);
Or if you're really whitespace-averse, here's a compromise:
var ar = {
inc: function(n) { return n + 1 },
dec: function(n) { return n + 2 }
};
ar.inc(1);
The var
keyword cannot follow an open parenthesis except in for (var ...)
. Maybe wrap the expression in a function:
ar = (function (n) {
return /* compute the value for ar here */;
})(1)
You can split the statement into:
var ar={inc:function(n){return n+1},dec:function(n){return n+2}}; ar.inc(1);
var ar = {
inc: function (n) { return n+1 },
dec: function (n) { return n+2 }
};
ar.inc(1);
Just declare it locally and invoke it in a seperate expression.
If you really want one expression I would recommend you declare a throwaway local variable __
var ar = {
inc: function (n) { return n+1 },
dec: function (n) { return n+2 }
}, __ = ar.inc(1);
The only way to invoke multiple expressions where one is a variable declaration is to declare multiple variables
If you want a local variable try declare it in a function,
(function () {
var ar={inc:function(n){return n+1},dec:function(n){return n+2}};
return ar;
})().inc(1)
not sure what is is you want to do, but this IIF (Immediately Invoked Function) may be an idea for you? Added a bit of spacing, which is ... advisable if you want to maintain your code.
alert(
(function(n){
n = n || 1;
return {
inc: function(n){ return n+1; },
dec: function(n){ return n+2; }
};
}(1)).inc(1)
); //=> 2
精彩评论