Copy the object

Shallow copy

/ / shallow copy
function shallowCopy(origin, target = {}) {
    for (const key in origin) {
        if(! origin.hasOwnProperty(key))break;

        target[key] = origin[key];
    }
    return target;
}

Copy the code

Deep copy

  • Deep copy recursively
/ / copy
function deepCopy(origin, target = {}) {
    for (const key in origin) {
        if (origin.hasOwnProperty(key)) {
            const val = origin[key];
            const arrType = '[object Array]';

            if (typeof val === 'object'&& val ! = =null) {
                target[key] = Object.prototype.toString.call(val) === arrType ? [] : {};
                deepCopy(val, target[key]);
            } else{ target[key] = val; }}}return target;
}

Copy the code
  • JSON
    • Disadvantages: Cannot copy methods
JSON.stringify();
JSON.parse();
Copy the code

This refers to the interview question

function Foo() {
    getName = function () {
        console.log(1);
    };
    return this;
}

Foo.getName = function () {
    console.log(2);
};
Foo.prototype.getName = function () {
    console.log(3);
};
var getName = function (){
    console.log(4);
};
function getName(){
    console.log(5);
}

Foo.getName();
getName();
Foo().getName();
new Foo.getName();
new Foo().getName();
new new Foo().getName();
Copy the code