MST

星途 面试题库

面试题:JavaScript 函数方法兼容性优化中的特性检测

假设要使用 `Object.assign` 方法来合并对象,但需要兼容不支持该方法的旧浏览器。请详细说明如何通过特性检测来实现兼容性优化,并且给出完整的代码实现,包括对 `Object.assign` 功能的模拟。
49.4万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 特性检测: 在使用 Object.assign 之前,先检查浏览器是否支持该方法。可以通过判断 Object.assign 是否为函数来进行特性检测。

  2. 代码实现

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 方法,实现对象合并功能,从而达到兼容性优化。