2

I'm writing a small utility that would make my working with canvas easier. But, when I run the code, I get the errors Uncaught SyntaxError: Unexpected token = (erik.core.js:5) and Uncaught ReferenceError: erik is not defined (test.html:14( (anonymous function).

Here is my HTML Code :

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ErikJs Unit Testing</title>
    <script src="erik.core.js"></script>
    ...
</head>
<body>
    ...
    <canvas id="myCanvas" width="500" height="400"></canvas>

    <script>
    var ctx = erik.initCanvas("#myCanvas");

        ctx.beginPath();
        ctx.moveTo(100, 200);
        ctx.lineTo(200, 300);
        ctx.stroke();
    </script>
</body>
</html>

And the JavaScript (erik.core.js) :

var Erik = function () {    
    this.author = "Erik Royall";
};

Erik.prototype.initCanvas = function ( element, y = '2d' ) {
    this.canvas = document.querySelectorAll( element );
    this.context = canvas.getContext( y );
    return this.context;
};

var erik = new Erik();
little pootis
  • 755
  • 1
  • 9
  • 22

2 Answers2

3

JavaScript doesn't have default parameter values. Remove the y = '2d' from the function declaration.

See also Set a default parameter value for a JavaScript function

Community
  • 1
  • 1
johusman
  • 3,472
  • 1
  • 17
  • 11
  • Funny thing though; when I copied the code in Firefox firebug console and ran it it didn't compain. Maybe this is someting that only works on some browsers. You can remove the y part and if it's not defined: y=(y===undefined)?'2d':y; – HMR Apr 17 '13 at 14:23
2

Further to johusman's answer, default parameters are now a part of ECMAScript 6, meaning this should be perfectly valid on JS engines supporting this feature. For engines not yet supporting default parameters, the esnext project provides a transpiler, available from the project GitHub page.

drewsberry
  • 534
  • 5
  • 8