Question

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();
Was it helpful?

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top