改进js代码以删除全局变量和函数

Improve js code to remove global variable and function

本文关键字:全局变量 函数 删除 js 代码 改进      更新时间:2023-09-26

我有一段js代码,我真的很想改进,但不确定如何改进。下面的工作版本有一个全局变量和一个单独的函数声明,我认为可以将其合并到一个匿名函数中(下面的代码片段:不工作)

任何帮助或建议都将不胜感激。

工作版本

var Data = {}; // would like to remove the global variable
function callBack() {
    $.ajax({
        url: "http://host/callBacks/script.js",
        //get and execute Script to process json data below
        dataType: "script"
    });
}

$(document).ready(function() {
    $.ajax({
        type: "Get",
        url: "http://host/data/json/",
        success: function(json) {
            Data = json; // Would like to just call the callback here
            callBack(Data);
        },
        error: function() {
            alert("error");
        }
    });
});

// Script which gets loaded from callBack
(function(Data) {
    var json = $.parseJSON(Data);
    $.each(json, function(i, v) {
        alert(v);
    });
})(Data);

所需代码:不工作

// Error: Length is null or not an object. In jQuery script
var Data = {}; // Ideally would like to remove this from global scope if possible
$(document).ready(function() {
    $.ajax({
        type: "Get",
        url: "http://host//data/json/",
        success: function(Data) {
            $.ajax({
                url: "http://host/callBacks/script.js",
                dataType: "script"
            });
        },
        error: function() {
            alert("error");
        }
    });
// Error: Length is null or not an object. In jQuery script

更新:根据adeneo的回答:仍然需要全局数据={};因为返回的立即执行的脚本将作为参数,我想是

var Data = {};
$(document).ready(function() {
    function doAjax() {
        return $.ajax({
            type: "GET",
            url: "http://host/data/json/"
        });
    }
    var XHR = doAjax();
    XHR.done(function(data) {
        Data = data; // <--- If I remove this I get Error:'length' is not or not an object
        $.ajax({
            url: "http://host/callBacks/script.js",
            dataType: "script"
        });
    }).fail(function() {
        alert("error");
    });
});

看起来已经足够好了。可能应该提到我正在IE 8中测试这个。限制更新标签

$(function() {
    function doAjax() { //put inside function
        return $.ajax({ //return deffered object
            type: "GET",
            url: "/data/json/" //X domain not supported
        });
    }
    var XHR = doAjax();  //do ajax call
    XHR.done(function(data) { // use deffered object
        var json = $.parseJSON(data); //why would you need to get an external script just to parse some JSON?
        $.each(json, function(i, v) {
            alert(v);
        });
    }).fail(function() {
        alert("error");
    });
});

您可以将全局变量和相关函数管理到一个类中,并在中创建一个对象

$(document).ready(function(){
    // Your code here !
});

像这样的东西怎么样

(function () {
    var myData_andMethod = {
        data : {},
        method : function (data) { this.data = JSON.parse(data); }
    };
    $.ajax({success : (function (obj) {
            var callback = obj.method.bind(obj);
            return function (data) {
                callback(data);
            };
        }(myData_andMethod)) //, error : function... url:"".....
    });
    //attach events here.
}());

你现在有0个全局任意项
除非现在你必须确保你对数据做了一些事情,一旦你的回调触发(或者它将永远消失,你再也无法访问它),或者你需要将它发送到已知范围内的某个函数(全局或应用程序的一部分或其他什么…),或者将它粘贴在is可公开访问的var中,以便可以在封闭后访问数据,并且所有回调都会返回。

即使是将myData_andMethod对象发送到其他将对象存储在其他位置的函数这样简单的事情。。。