I have written the following function:
function MyTest(element, no, start=0) {
this.no = no;
this.element = element;
this.currentSlide = start;
self.start();
}
JSLint plains:
Expected ')' to match '(' from line 4 and instead saw '='.
What is wrong with this? Is it the default value I've set?
I have written the following function:
function MyTest(element, no, start=0) {
this.no = no;
this.element = element;
this.currentSlide = start;
self.start();
}
JSLint plains:
Expected ')' to match '(' from line 4 and instead saw '='.
What is wrong with this? Is it the default value I've set?
Share Improve this question asked Dec 10, 2013 at 9:35 user2807681user2807681 993 silver badges9 bronze badges1 Answer
Reset to default 7JavaScript doesn't have default values for arguments (yet; it will in the next version, and as Boldewyn points out in a ment, Firefox's engine is already there), so the =0
after start
is invalid in JavaScript. Remove it to remove the error.
To set defaults values for arguments, you have several options.
Test the argument for the value
undefined
:if (typeof start === "undefined") { start = 0; }
Note that that does not distinguish between
start
being left off entirely, and being given asundefined
.Use
arguments.length
:if (arguments.length < 3) { start = 0; }
Note, though, that on some engines using
arguments
markedly slows down the function, though this isn't nearly the problem it was, and of course it doesn't matter except for very few functions that get called a lot.Use JavaScript's curiously-powerful
||
operator depending on what the argument in question is for. In your case, for instance, where you want the value to be0
by default, you could do this:start = start || 0;
That works because if the caller provides a "truthy" value,
start || 0
will evaluate to the value given (e.g.,27 || 0
is27
); if the caller provides any falsey value,start || 0
will evaluate to0
. The "falsey" values are0
,""
,NaN
,null
,undefined
, and of coursefalse
. "Truthy" values are all values that aren't "falsey".
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744292891a4567118.html
评论列表(0条)