简体   繁体   中英

How can I call a nested function from outside its parent function?

I am working on an HTML file with JavaScript in it.

Here is the JavaScript code:

var dImage = new Image();

var drawing = (function () {

    .
    .
    .
    .

    redrawing = function () {
        context.drawImage(dImage, dX, dY, dWidth, dHeight);
    },

    init = function () {
        dImage.src = "images/d.png";
        redrawing();
    };

    return {
        init: init
    };

}());

function updateImage(dSrc){
    dImage.src = dSrc;
    // Call redrawing here
}

In the HTML I call

drawing.init();

and it is working fine. Also I can change the image source by calling

updateImage("images/d2.png");

and it is working for changing the source.

But I need to call redrawing() in the method updateImage() to refresh the image.

I try to call it in many ways (for example, drawing.redrawing(); ) but there is no response from redrawing() .

If you want to be able to call the redrawing function from outside of the function it's defined in, you need to return it from that function, just like you've done with init :

var drawing = (function () {

    .
    .
    .
    .

    return {
        init: init,
        redrawing: redrawing
    };
}());

Make redrawing public:

return {
    init: init,
    redrawing: redrawing
};

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