Vitaminaq / interview-collection

前端面试合集
3 stars 0 forks source link

实现一个非原生类(数组, Map/Set 等)的浅拷贝函数 #10

Open Vitaminaq opened 2 years ago

Vitaminaq commented 2 years ago

此函数接收一个非原生类对象(可能有自定义的原型链), 返回一个此对象的浅拷贝。

// 测试代码
class UserModel {
    constructor(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
    }
    fullName() {
      return this.firstName + ' ' + this.lastName;
    }
}
const user = new UserModel('Hello', 'World');
const user2 = shallowCopy(user);
user2.firstName = 'Hello 2';
user2.lastName = 'World 2';

console.log(user2 instanceof UserModel); // true
user.fullName(); // 'Hello World'
user2.fullName(); // 'Hello 2 World 2'
Vitaminaq commented 2 years ago
// 浅拷贝
function shallowCopy(obj) {
    if (obj instanceof Map) return new Map(obj);
    if (obj instanceof Set) return new Set(obj);
    // if (obj instanceof Array) return obj.slice();

    const o = obj instanceof Array ? [] : {};
    Object.assign(o, obj);

    // 拷贝自定义原型链
    o.__proto__ = obj.__proto__;
    return o;
}