如何在localforage原型中识别'this'?

时间:2017-01-10 15:03:13

标签: javascript prototype this localforage

我正在尝试使用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(); })));

0 个答案:

没有答案