0

我正在尝试使用 localforage 作为存储数据的方式,但不想重写相同的代码来存储和加载大型数据数组,因此我决定使用包含所述函数的原型制作一个对象。一个用于setItem,一个用于getItem。我首先配置我的 localforage,然后定义我的函数,然后定义它的原型。

当我尝试在原型中运行它时,在 setArray 中,this.forageName 是未定义的。为什么它是未定义的,我如何让它被识别?

我希望原型能够识别 this.forageName 何时被调用,它将被实例化对象调用,并通过使用“this”来引用实例化对象。

localforage.config({
          description: 'Storage medium for caching 2d arrays.'
    });

    /**  
    *   This function is based on Localforage which uses a promise/callback API.
    *   Promise chains make sure that all values are returned before moving onto the next step.
    *
    *   ForageStorage parses through a 2d array and uses localforage to store each array in key-value pairs,
    *   where the first item in each sub-array is the key and the entire sub-array is the value.
    *   @namespace ForageStorage
    *   @param {string} forageName - The name of the localforage object that this object will instantiate.
    *   @param {array[]}  arrayToStore - The array of arrays to parse through and store.
    */
    function ForageStorage(forageName, arrayToStore){
        this.forageName = localforage.createInstance({name: forageName});
        this.arrayToStore = arrayToStore;
        this.retrievedArray = [];
        this.promiseArray = [];
    };


    ForageStorage.prototype = {

        setArray:        function (){
            this.promiseArray = this.arrayToStore.map(function (item) { return this.forageName.setItem(item[0].toString(), item)});
            return Promise.all(promiseArray);
        },
        getArray: function () {
            this.forageName.keys()
            .then(function (keys) {
                this.retrievedArray = keys.map(function (item) {return this.forageName.getItem(item)})
            })
            return Promise.all(retrievedArray);
        },
    };

var forageStorage = new ForageStorage("myStorage",textData);

forageStorage.setArray()
.then(forageStorage.getArray())
.then(console.log(param.map(function () { return item.toString(); })));
4

0 回答 0