Uncaught TypeError: undefined is not a function

不打扰是莪最后的温柔 提交于 2019-12-12 01:36:06

问题


Button.js:

(function () {
    function Button(label) {
        console.log(label);
    }
}());

demo.html:

<html>

<head>
    <script src="../../lib/easeljs-0.7.1.min.js"></script>
    <script src="Button.js"></script>
    <script>
        window.onload = function() {
            var canvas, stage, button;
            canvas = document.getElementById("canvas");
            stage = new createjs.Stage(canvas);
            button = new createjs.Button("Anything");
            stage.addChild(button);
            stage.update();
        }
    </script>
</head>

<body>
    <canvas id="canvas" width=200 height=200>Canvas is not supported</canvas>
</body>

</html>

for the line button = new createjs.Button("Anything"); Error: Uncaught TypeError: undefined is not a function Why i am getting this error?


回答1:


It is because the Button is not in a global scope or window.

You don't need IEFE here. Remove it:

function Button(label) {
   console.log(label);     
}

If you want it with IEFE, then do this:

$(function () {
    window.Button = function (label) {
        console.log(label);
    }
});



回答2:


If you want to access Button by using createjs.Button, then you must create Button on the createjs object:

createjs.Button = function(label){
    console.log(label);
};

The above will work in any scope, including the global and your function expression, because createjs is in the global scope. Now you can do:

button = new createjs.Button("Anything");


来源:https://stackoverflow.com/questions/23930899/uncaught-typeerror-undefined-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!