Bigcommerce模板:Javascript错误“对象不支持Windows Safari和IE中的属性或方法'assign'”

时间:2016-08-03 23:36:28

标签: javascript bigcommerce

不确定发生了什么,但此错误阻止了页面显示。

错误消息指向我的bundle.js文件(带有webpack,babel等的模板包),特别是指向stencil-utils包中的Object.assign()方法。它是@bigcommerce/stencil-utils/src/lib/request.js

的第27行

以下是产生错误的代码部分。

const defaultOptions = {
    method: 'GET',
    remote: false,
    requestOptions: {
        formData: null,
        params: {},
        config: {},
        template: [],
    },
};
const options = Object.assign({}, defaultOptions, opts);
const data = options.requestOptions.formData ? options.requestOptions.formData : options.requestOptions.params;
const headers = {
    'stencil-config': options.requestOptions.config ? JSON.stringify(options.requestOptions.config) : '{}',
    'stencil-options': '{}',
};

可能导致这种情况的任何想法?

1 个答案:

答案 0 :(得分:3)

您正在使用Object.assign方法,但并非所有浏览器都支持此方法。 Internet Explorer和Safari(适用于Windows)都不再正式更新。

无论如何,page中有Object.assign的填充物。您可以将其应用于代码的顶部。

这是我自己的polyfill,它可以选择性地避免创建对象/数组引用(使用任何其他接口的对象除外,如Image等)。

typeof Object.assign !== "function" &&

(function() {

    /**
     * Return main instance of value.
     * @param {...} value
     * @returns 
     */
    function getMainInstance(value) {
        // get instance in this format: [object Instance]
        var ic = Object.prototype.toString.call(value);
        // returns string between '[object ' and ']'
        return ic.substring(ic.indexOf(" ") + 1, ic.lastIndexOf("]")).toLowerCase();
    }


    Object.assign = function(target) {

        /* check if target isn't a object */
        if (typeof target !== "object") target = {};

        /* last target path */
        var lastPath = target;

        /* list containing target paths */
        var locations = [];

        /* consume specific array/object */
        function consume(source) {
            /* iterate each property to copy */
            for (var i in source) {
                var instance = getMainInstance(source[i]);
                if (instance === "object" || instance === "array") {
                    lastPath =
                    lastPath[i] =
                    locations[locations.length] = (instance === "array" ? [] : {})

                    consume(source[i]);

                } else {
                    lastPath[i] = source[i];
                }
            }

            var len = -- locations.length;
            lastPath = locations[--len] || target;

        }

        for (var i = 1, source; source = arguments[i]; i++) {
            if (typeof source === "object") consume(source);
        }

        return target;
    };

})();