javascript - JS: How to fix "Expected ')' to match '(' from line 4 and instead saw &

I have written the following function:function MyTest(element, no, start=0) {this.no = no;this.elemen

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 badges
Add a ment  | 

1 Answer 1

Reset to default 7

JavaScript 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.

  1. 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 as undefined.

  2. 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.

  3. 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 be 0 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 is 27); if the caller provides any falsey value, start || 0 will evaluate to 0. The "falsey" values are 0, "", NaN, null, undefined, and of course false. "Truthy" values are all values that aren't "falsey".

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744292891a4567118.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信