如何在 javascript 中保存对象变量的状态

How do i save state of object vars in javascript?

本文关键字:对象 变量 状态 保存 javascript      更新时间:2023-09-26

这是我的代码:

var theObj = {
    localepath:false,
    settings:false,
    localeObj:false,
    callAjax: function(relative_path, callback){
        var Ajax =  new XMLHttpRequest();
        var serialized = false;
        Ajax.onreadystatechange = function() {
            //Since what we are calling a local file. we cannot get a 200 OK Status.
            //So We check only the readystate
            if(Ajax.readyState==4){
                serialized = Ajax.responseText;
                callback(serialized);
            }
        }
        Ajax.open("GET",relative_path, true);
        Ajax.send();    
    },
    readSettings: function(callback){
        var data = this.callAjax('settings.json', function(data){
            this.settings = JSON.parse(data);
            callback(this.settings);
        });
    },
    readLocale: function(localepath, callback){
        var data = this.callAjax('locale/'+localepath+'.json', function(data){
            this.localeObj = JSON.parse(data);
            callback();
        });
    },
    writeContent: function(id, typeofElement, content){
        var currentElement = document.createElement(typeofElement);
        currentElement.setAttribute('id', id);
        currentElement.innerHTML = this.l10n(content);
        document.body.appendChild(currentElement);
    },
    l10n: function(content){
        var localeObject =  this.localeObj;
        alert(localeObject); //<< This will alert the  cause
        var arr = content.split(" ").reverse(); //Split by space. and reverse (actually non-reversed) the order
        var newArr =[]; //Container
        for (var i = arr.length - 1; i >= 0; i--) {
            // if the word does not have one-to-one mapping:
            if(localeObject[arr[i]] == undefined){
                if(isNaN(Number(arr[i]))){
                //^^ if the word is not a number
                newArr.push(arr[i]); //do not translate.
                } else { //if the word is collection of digits
                    var nums = arr[i].split('').reverse(); //Same old split and (non)-reverse
                    var convNums = []; //Same old container
                    for (var j = nums.length - 1; j >= 0; j--) {
                        convNums.push(localeObject[nums[j]]);
                        //iterate and push digits
                    }
                    newArr.push(convNums.join('')); //Make those digits a word! :)
                }
            } else { //This means the word has a one-to-one mapping:
                newArr.push(localeObject[arr[i]]);
            }
        }
        return newArr.join(" "); //Join all with spaces.
    },
    setLocalePath: function(path_to_locale){
        this.localepath = path_to_locale;
    },
    getLocaleDefault:function(settings){
        return settings.locale[settings.defaultLocale];
    }
};

现在,当我这样做时:

theObj.readSettings(function(settings){
        theObj.readLocale(theObj.getLocaleDefault(settings), function(){
            //Start Writing contents here               
            theObj.writeContent('top', 'div', 'looma-f5');
            theObj.writeContent('content', 'div','test 132');
    });
});

它两次发出错误警报,这意味着该方法theObj.readLocale()没有将内容保存到this.localeObj ?为什么会这样?我尝试做var newObj = new theObj();但没有奏效。有什么解决方法吗?

这种类型的

问题是由于对this关键字的理解较少而引起的。这里的主要问题是该方法的localeObj属性从未保存,因为this是从回调内部引用的,因此没有引用对象。可以做的一件事是:

.....
    readLocale: function(localepath, callback){
        var that = this; //Now `that` = `this` references the object
        var data = this.callAjax('locale/'+localepath+'.json', function(data){
            that.localeObj = JSON.parse(data);
            callback(); 
        });
    },
....