javascript - 未捕获的类型错误 : undefined is not a function when including javascript class in a seperate file

标签 javascript class include raphael

我是 Javascript 类的新手,但我正在尝试使用 Raphael 创建一个简单的绘图应用程序。我目前遇到的问题是某些代码在同一个文件中时有效,但是当我尝试将其取出并包含时,它给了我:

Uncaught TypeError: undefined is not a function. 

我的第一个想法是文件没有被正确包含,所以我检查了一下,chrome 的开发帮助工具显示资源很好。

代码在名为 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"
    );
};

使用它的相关代码是:

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

我以前从未在 javascript 中使用过类,也没有包含我自己制作的 js 文件,所以对此事的任何了解,而不仅仅是修复会很好。另外,如果您认为有更好的方法来解决我一般如何做这件事,请告诉我!多谢!

最佳答案

出现此问题是因为您的对象名称和类名称相同。尝试像这样给您的对象一个不同的名称:

var newLine=new line(paper);

此外,当我尝试为对象和类提供相同的名称时,我得到 TypeError: line is not a constructor in Firebug 并且当我将代码放入 line.js 或 window.onload 之前的地方时会发生此错误。

关于javascript - 未捕获的类型错误 : undefined is not a function when including javascript class in a seperate file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15776887/

相关文章:

ios - 如何在实例方法中访问类方法变量或对两者使用公共(public)变量?

使用 include 和 extend 的 Ruby 模块 mixin - 它是如何工作的?

javascript - D3 : How to set symbols insted of points in a ScatterPlot

javascript - 使用过滤,优先级和最小循环将数组转换为对象

javascript - Browserify 在多次 require 调用时仅执行一次模块代码

javascript - <p :commandButton> not getting scrolled along with the <p:scrollPanel>

asp.net - 在ASP.NET中导入类

class - “POCO”定义

jquery - 当已经在脚本中时,如何使用 jQuery 将脚本写入页面

c++在我的makefile中包括特征