为什么在此代码中返回undefined?

时间:2014-08-22 14:08:17

标签: javascript

我有以下模块来设置和读取键/名称对。每次我调用Store.save('name','Jason')“返回undefined并且我不确定原因。任何关于为什么会发生这种情况的想法都会非常感激。这是代码:

var config = {
    trackEvents: ['focus', 'blur'],
    trackFields: ['input[type=text]', 'select', 'input[type=radio]', 'input[type=checkbox]'],
    currentFocused: '',
    lastFocused: '',
    enableDoNotTrack: false,
    debug: true,
    cookieExpiry: 30
};

var Store = (function () {
    // Set keyvalue pair in either localstorage or a cookie
    function _set(key, value) {
        // If value detected set or modify the key
        if (typeof value !== "undefined" && value !== null) {
            if (localStorage) {
                localStorage.setItem(key, value);
            } else {
                _setCookie(key, value, config.cookieExpiry);
            }
        }
        // if value is null or undefined, delete the key
        if (value === null) {
            if (localStorage) {
                localStorage.removeItem(key);
            } else {
                _setCookie(key, null, -1);
            }
        }
    }

    function _get(key) {
        var val = '';
        if (localStorage) {
            val = localStorage.getItem(key);
        } else {
            val = _getCookie(key);
        }
        return val;
    }

    // Set cookie
    function _setCookie(key, value, exp) {
        var d = new Date();
        d.setTime(d.getTime() + (exp * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toGMTString();
        document.cookie = key + "=" + value + "; " + expires;
    }

    // Read cookie  
    function _getCookie(key) {
        var name = key + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
        }
        return "";
    }
    return {
        save: _set,
        read: _get
    };
})(config);

1 个答案:

答案 0 :(得分:0)

从“Store”返回的对象没有“set”属性。但它有一个“save”属性,其值是对闭包中“_set”函数的引用。

编辑并且正如Patrick Evans在评论中指出的那样,“_ set”方法不返回值,所以即使你正确地调用“save”,它也会返回undefined