使JS本地功能可全局访问

tar*_*rka 5 javascript scope function

我在函数内部有一个函数,我需要直接访问.

//#############################################################
//# Global vars
//#############################################################
var canvasWidth = 585;
var canvasHeight = 780;

//#############################################################
//# Init the canvas
//#############################################################
window.onload = function() {
    initStage();
};

//#############################################################
//# Init the main stage
//#############################################################
function initStage() {

    //*************************************************************
    //* Create a stage to work with
    //*************************************************************
    var stage = new Kinetic.Stage({
        container: "container",
        width: canvasWidth,
        height: canvasHeight
    });

    var layerOne = new Kinetic.Layer();
    var imageObj = new Image();

    //*************************************************************
    //* Load the image into a layer on the stage
    //*************************************************************
    ... Some Code ...

    //*************************************************************
    //* Set the hidden field value to the canvas dataURL
    //*************************************************************
    function autoSave(){
        stage.toDataURL({
            callback: function(dataUrl){
                document.getElementById("mapping-form:hiddenDataURL").value = dataUrl;
                console.log("Auto Save excecuted");
            }, 
            mimeType: 'image/jpeg', 
            quality: 1.0
        });        
    }

    //*************************************************************
    //* Function called to add text to the stage
    //*************************************************************
    ... Some Code ...    

        layerTwo.add(txt);
        stage.add(layerTwo);

    });

}
Run Code Online (Sandbox Code Playgroud)

我正在尝试访问autoSave()(反过来需要来自父函数的stage var).我理解为什么我无法访问它,但我很难看到如何改变代码以使其可访问.

我的第一个想法是简单地声明一个'更高范围'的var并为其分配函数.问题是(据我所知),这实际上不允许我在请求的时间执行autoSave().

抱歉"这个问题的基本性质,我是JS的新手,我认为这将是根本的!

Gri*_*rim 13

您可以使您的函数可以全局访问,并且仍然可以在创建它的范围内引用变量.只需在窗口范围内创建并分配它 - 例如,而不是将其定义为:

function autoSave() {
    // ... code ...
}
Run Code Online (Sandbox Code Playgroud)

声明为:

window.autoSave = function() {
    // .... code ....
}
Run Code Online (Sandbox Code Playgroud)

您现在可以在任何地方调用它(前提是已经调用initStage方法来首先声明它).


Wil*_*ker 5

您可以将autoSave函数分配给该对象,即

function initStage() {        
    ... Some Code ...
    this.autoSave = function(){
        ... Some Code ...        
    }

    return this;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以打电话

initStage().autoSave();
Run Code Online (Sandbox Code Playgroud)