简体   繁体   中英

Uncaught TypeError: undefined is not a function

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?

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);
    }
});

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM