【问题标题】:How do i use object.assign in internet explorer 11我如何在 Internet Explorer 11 中使用 object.assign
【发布时间】:2020-12-01 10:22:09
【问题描述】:

我有使用 Object.assign 的 javascript 代码,这在除 Internet Explorer 11 之外的所有浏览器中都能正常工作。

在这个例子中 Object.assign(options, { 失败,对象不支持属性或方法“分配”

如何重写它以兼容包括 IE11 在内的所有浏览器?

var options = {
    authorization: braintreePayment.token,
    container: '#braintree-container',
    vaultManager: true,
    threeDSecure: threeDSecureFlag,
};

if (braintreePayment.isPaypal) {
    Object.assign(options, {
        paypal: {
            flow: 'vault',
        },
    });
}

if (braintreePayment.isPaypalCredit) {
    Object.assign(options, {
        paypalCredit: {
            flow: 'checkout',
            amount: braintreePayment.total,
            currency: braintreePayment.currency,
        },
    });
}

if (braintreePayment.isApplePay) {
    Object.assign(options, {
        applePay: {
            displayName: braintreePayment.companyName,
            paymentRequest: {
                total: {
                    label: braintreePayment.companyName,
                    amount: braintreePayment.total,
                },
                requiredBillingContactFields: ['postalAddress'],
            }
        }
    });
}

【问题讨论】:

    标签: javascript object assign


    【解决方案1】:

    你可以使用来自 MDN 的这个 polyfill https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

    if (typeof Object.assign !== 'function') {
      // Must be writable: true, enumerable: false, configurable: true
      Object.defineProperty(Object, "assign", {
        value: function assign(target, varArgs) { // .length of function is 2
          'use strict';
          if (target === null || target === undefined) {
            throw new TypeError('Cannot convert undefined or null to object');
          }
    
          var to = Object(target);
    
          for (var index = 1; index < arguments.length; index++) {
            var nextSource = arguments[index];
    
            if (nextSource !== null && nextSource !== undefined) { 
              for (var nextKey in nextSource) {
                // Avoid bugs when hasOwnProperty is shadowed
                if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                  to[nextKey] = nextSource[nextKey];
                }
              }
            }
          }
          return to;
        },
        writable: true,
        configurable: true
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-01
      • 2016-07-01
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 2018-09-19
      相关资源
      最近更新 更多