tags: JavaScript 前端
author: zhanglei
data: 2023-12-07
Object.assin 不支持低版本浏览器
IE适配
IE11非兼容模式下, 比较新的ES6语法不能使用, Object.assin就是其中之一, 可通过一下方法适配
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
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
});
}
const returnedTarget = Object.assign(target, source);
console.log(target);