面试题答案
一键面试-
特性检测: 在使用
Object.assign
之前,先检查浏览器是否支持该方法。可以通过判断Object.assign
是否为函数来进行特性检测。 -
代码实现:
if (typeof Object.assign!== 'function') {
// 模拟 Object.assign 功能
Object.assign = function(target) {
'use strict';
if (target === null || target === undefined) {
throw new TypeError('Cannot convert undefined or null to object');
}
let to = Object(target);
for (let i = 1; i < arguments.length; i++) {
let nextSource = arguments[i];
if (nextSource!== null && nextSource!== undefined) {
for (let nextKey in nextSource) {
// 避免原型链上的属性
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
};
}
通过上述代码,先进行特性检测,如果浏览器不支持 Object.assign
,则定义一个模拟的 Object.assign
方法,实现对象合并功能,从而达到兼容性优化。