JavaScript 错误;在本地尝试时

发布于 2024-11-05 00:32:58 字数 1919 浏览 1 评论 0原文

下面的代码给出“未捕获的类型错误:无法调用未定义的方法'getContext'”。该代码是我使用模块模式移植画布应用程序的实验,如此处所述。

请在 jsfiddle 中找到相同的代码,效果很好。

谢谢。

//====test.html ========

<html>
<head>
    <title>Location</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript" src="test.js"></script>
</head>

<body>
<canvas id="cvs" height="600" width="800"></canvas>
</body>
</html>

//==test.js ========

if (typeof (NS) === 'undefined') {
    NS = {};
}

NS.AppName = (function ($) {
// Private members
    /*var _first = function () {
    },
    _second = function () {
    },*/
    var _cvs = $("#cvs");
    var _ctx = _cvs.get(0).getContext("2d");    

    var _privateVar = "privateVar: accessed from within AppLaunch.Admin namespace";
    // Private Methods
    var _privateMethod = function () {
       log("privateMethod: accessed only from within AppLaunch.Admin");
    }; // Last variable in a chain must always end with ; before the return {}

    function log() {
        if (window.console && window.console.log)
            window.console.log('[AppName] ' + Array.prototype.join.call(arguments, ' '));
    };

    return {
        init: function () {
        },

        // Public
        myPublicMethod: function() {
            //alert("myPublicMethod" + _cvs.height());
            _ctx.fillRect(25,25,100,100);
    _ctx.clearRect(45,45,60,60);
    _ctx.strokeRect(50,50,50,50);
        }
    }
})(jQuery); 

// Initialize
jQuery().ready(function() {
    NS.AppName.init()
    NS.AppName.myPublicMethod();
});  

the below code gives "Uncaught TypeError: Cannot call method 'getContext' of undefined". The code is my experiment to port a canvas app using module pattern as described here.

Please find the same code in jsfiddle, which works fine.

thanks.

//====test.html ========

<html>
<head>
    <title>Location</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript" src="test.js"></script>
</head>

<body>
<canvas id="cvs" height="600" width="800"></canvas>
</body>
</html>

//==test.js ========

if (typeof (NS) === 'undefined') {
    NS = {};
}

NS.AppName = (function ($) {
// Private members
    /*var _first = function () {
    },
    _second = function () {
    },*/
    var _cvs = $("#cvs");
    var _ctx = _cvs.get(0).getContext("2d");    

    var _privateVar = "privateVar: accessed from within AppLaunch.Admin namespace";
    // Private Methods
    var _privateMethod = function () {
       log("privateMethod: accessed only from within AppLaunch.Admin");
    }; // Last variable in a chain must always end with ; before the return {}

    function log() {
        if (window.console && window.console.log)
            window.console.log('[AppName] ' + Array.prototype.join.call(arguments, ' '));
    };

    return {
        init: function () {
        },

        // Public
        myPublicMethod: function() {
            //alert("myPublicMethod" + _cvs.height());
            _ctx.fillRect(25,25,100,100);
    _ctx.clearRect(45,45,60,60);
    _ctx.strokeRect(50,50,50,50);
        }
    }
})(jQuery); 

// Initialize
jQuery().ready(function() {
    NS.AppName.init()
    NS.AppName.myPublicMethod();
});  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

满栀 2024-11-12 00:32:58

您的 ready 处理程序语法不正确 - 尝试以下操作:

jQuery(document).ready(function() {
    NS.AppName.init();
    NS.AppName.myPublicMethod();
});

或者

jQuery(function() {
    NS.AppName.init();
    NS.AppName.myPublicMethod();
});

Your ready handler syntax is incorrect - try this:

jQuery(document).ready(function() {
    NS.AppName.init();
    NS.AppName.myPublicMethod();
});

Or

jQuery(function() {
    NS.AppName.init();
    NS.AppName.myPublicMethod();
});
心房敞 2024-11-12 00:32:58

您收到错误的原因是自执行匿名函数NS.AppName 的 > 在适当的位置(定义它的地方)调用,而不是在 DOM 准备好时调用。

NS.AppName = (function ($) {
  //1: some code
  return function(){...}//2
}(jQuery));//3

$(function(){
  NS.AppName();//4
});

第 3 行自执行部分。它调用上面声明的匿名函数。

在调用第 3 行期间,将执行匿名函数的主体(包括第 1 行,但不执行第 2 行函数内的任何内容) )。如果发生这种情况时文档没有加载(例如:如果脚本位于头部),那么它将失败,因为 DOM 中还没有 $("#cvs")

第 4 行 将调用第 2 行定义的函数当 DOM 完全加载时($(f) 为相当于 $(document).ready(f))。

以下是有关自执行匿名函数或使用更好的名称的更多信息“

您可以通过三种方式修复脚本:

  • 从匿名函数中删除对 DOM 的任何引用,并将它们移到返回的函数中(我会这样做,它只是一个元素...)
  • 将整个脚本包装在 jQuery(function($){...(您可以在这里安全地使用 $,因此不需要匿名函数)...}); - 执行一切都在 DOM 上准备好
  • 将其移动到页面底部(不理想,但它可以工作)

The reason you get an error is that the self executing anonymous function used to initialize NS.AppName is invoked in place (right where it is defined), and not when the DOM is ready.

NS.AppName = (function ($) {
  //1: some code
  return function(){...}//2
}(jQuery));//3

$(function(){
  NS.AppName();//4
});

line 3 is the self executing part. It calls the anonymous function declared above.

During the call of line 3 the body of the anonymous function will be executed (including line 1, but not anything inside the function at line 2). If the document is not loaded when this happens (ex: if the script is in the head), than it will fail because there is no $("#cvs") in the DOM yet.

Line 4 will call the function defined at line 2 when the DOM is fully loaded ($(f) is equivalent to $(document).ready(f)).

Here is some more info about self executing anonymous functions, or using a better name "Immediately-Invoked Function Expression"

You can fix the script in three ways:

  • Remove any references to the DOM from the anonymous function, and move them in the returned one (I'd do this, it's just one element...)
  • Wrap the entire script in jQuery(function($){...(you can safely use $ here, so no need for the anonymous functions)...}); - execute it all on DOM ready
  • Move it at the bottom of the page (not ideal, but it would work)
烧了回忆取暖 2024-11-12 00:32:58

我没有收到错误。但也许你在这里 c/ping 的翻译过程中丢失了一些东西。也许(这只是一个猜测),放一个 ;在 NS.AppName.init() 的末尾,也许您会遇到一些奇怪的空白/返回...

I don't get an error. But perhaps something is lost in translation from you c/ping it here. Perhaps (and this is just a guess), put a ; on the end of that NS.AppName.init() maybe you have some funky whitespace/returns going on there...

高跟鞋的旋律 2024-11-12 00:32:58

将 JS 移动到 body 解决了问题:

    <html>
<head>
    <title>Location</title>
</head>

<body>
<canvas id="cvs" height="600" width="800"></canvas>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript" src="test.js"></script>
</body>
</html>

或者

    <html>
<head>
    <title>Location</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>

<body>
<canvas id="cvs" height="600" width="800"></canvas>     
    <script type="text/javascript" src="test.js"></script>
</body>
</html>

Moving the JS to body solved the problem:

    <html>
<head>
    <title>Location</title>
</head>

<body>
<canvas id="cvs" height="600" width="800"></canvas>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript" src="test.js"></script>
</body>
</html>

or

    <html>
<head>
    <title>Location</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>

<body>
<canvas id="cvs" height="600" width="800"></canvas>     
    <script type="text/javascript" src="test.js"></script>
</body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文