简体   繁体   中英

How to call javascript methods that are not in scope but utilise .call(this)

I am unsure on how to call these functions such as inventoryCheck in a web browser (chrome) console when it seems not visible. Is there a way I can call this? Thanks!

Below is a snippet of a javascript file.

(function() {
    var CC, addToBagCheck, addToCartError, addToCartRequest, addToCartSuccess, availableSizes, displayCorrectShoe, inventoryCheck, isValidJSON, processInventory, selectSize, showBuy, showError, showSoldOut,
        slice = [].slice,
        bind = function(fn, me) {
            return function() {
                return fn.apply(me, arguments);
            };
        };

    inventoryCheck = function() {
        return availableSizes(function(product) {
            return processInventory(product);
        });
    };

    window.captchaResponse = function(response) {
        $('#captcha').addClass('checked');
        $('#flashproductform').append('<input class="captcha-duplicate" type="hidden" name="x-PrdRt" value="' + response + '">');
        return addToBagCheck();
    };

}).call(this);

You cannot. inventoryCheck is defined inside a closure. In order to call them globally (like in the console), you must define them on the window object. Since your closure appears to have window as its context (by calling it using this as context), then you can define inventoryCheck like:

this.inventoryCheck = function(){...}

Note that defining stuff on the global object is a bad idea. Consider attaching everything to a single global object you own. This reduces your footprint on the global object to just a single object. The following pattern is better:

;(function(ns){

  ns.inventoryCheck = function(){...}

  // the rest of the code

})(this.myGlobal = this.myGlobal || {});

// Usage

myGlobal.inventoryCheck(...);

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