samuraiseoul
samuraiseoul

Reputation: 2967

Uncaught TypeError: undefined is not a function when including javascript class in a seperate file

Im new to classes in Javascript, but I trying to create a simple drawing app, with Raphael. The problem I have currently is with some code that works when it is in the same file, but then when I try to take it out and include it, it gives me:

Uncaught TypeError: undefined is not a function. 

My first thought was that the file isn't getting included correctly, so I checked, and chrome's dev helper tools show the resource just fine.

The code is in a file called line.js:

function line(paper) {
    this.x1 = null;
    this.x2 = null;
    this.y1 = null;
    this.y2 = null;

    this.paper = paper;
};

line.prototype.draw = function(){
    this.paper.path(
        "M " + this.x1 + " " + this.y1 +
        " l " + (this.x2 - this.x1) + " " + (this.y2 - this.y1) + " z"
    );
};

and the code in question that is using it is:

<script type="text/javascript" src="../js/raphael-min2.1.js"></script>
<script type="text/javascript" src="../js/line.js"></script>

<script>
window.onload = function() {  
    var paper = new Raphael($('#canvas')[0], 500, 500);
    var canvas =$('#canvas');    
    var line = new line(paper);

    canvas.mousedown(function(e){
        line.x1 = e.offsetX;
        line.y1 = e.offsetY;
    });

    canvas.mouseup(function(e){
        line.x2 = e.offsetX;
        line.y2 = e.offsetY;
        line.draw();
    });
};
</script>

I've never used classes in javascript before, nor included js files that i've made myself, so any light on the matter, not just a fix would be nice. Also if you think there is a better approach to how Im doing this in general, please let me know! Thanks a lot!

Upvotes: 4

Views: 5090

Answers (1)

haitaka
haitaka

Reputation: 1856

This problem occurs because your object's name and class' name is identical. Try to give a different name to your object like this:

var newLine=new line(paper);

Moreover, when I try to give identical name to both the object and class, I get TypeError: line is not a constructor in Firebug and this error occurs when I put code into line.js or the place before window.onload.

Upvotes: 3

Related Questions