简体   繁体   中英

Accessing a function within a function from outside in javascript

I have a nested function that I want to call from outside.

var _Config = "";
var tourvar;
function runtour() {
    if (_Config.length != 0) {
        tourvar = $(function () {
            var config = _Config,
                autoplay = false,
                showtime,
                step = 0,
                total_steps = config.length;
            showControls();
            $('#activatetour').live('click', startTour);
            function startTour() {
            }
            function showTooltip() {
            }
        });
    }
}
function proceed() {
    tourvar.showTooltip();
}
$(document).ready(function () {
    runtour();
});

I was hoping to call it by tourvar.showTooltip(); but I seem to be wrong :) How can I make showTooltip() available from outside the function?

since my previous answer was really a hot headed one, I decided to delete it and provide you with another one:

var _Config = "";
var tourvar;

// Module pattern
(function() {
    // private variables
    var _config, autoplay, showtime, step, total_steps; 

    var startTour = function() { };

    var showTooltip = function() { };

    // Tour object constructor
    function Tour(config) {
        _config = config;
        autoplay = false;
        step = 0;
        total_steps = _config.length;

        // Provide the user with the object methods
        this.startTour = startTour;
        this.showTooltip = showTooltip;
    }

    // now you create your tour
if (_Config.length != 0) {
        tourvar = new Tour(_Config);
    }
})();

function proceed() {
    tourvar.showTooltip();
}
$(document).ready(function () {
    runtour();    
});
function outerFunction() {
    window.mynestedfunction = function() {
    }
}
mynestedfunction();

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