Static variables in JavaScript

后端 未结 30 2224
别那么骄傲
别那么骄傲 2020-11-22 01:55

How can I create static variables in Javascript?

30条回答
  •  被撕碎了的回忆
    2020-11-22 02:32

    Working with MVC websites that use jQuery, I like to make sure AJAX actions within certain event handlers can only be executed once the previous request has completed. I use a "static" jqXHR object variable to achieve this.

    Given the following button:

    
    

    I generally use an IIFE like this for my click handler:

    var ajaxAction = (function (jqXHR) {
        return function (sender, args) {
            if (!jqXHR || jqXHR.readyState == 0 || jqXHR.readyState == 4) {
                jqXHR = $.ajax({
                    url: args.url,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify($(sender).closest('form').serialize()),
                    success: function (data) {
                        // Do something here with the data.
                    }
                });
            }
        };
    })(null);
    

提交回复
热议问题