美文网首页
JS工具-类型判断和深拷贝

JS工具-类型判断和深拷贝

作者: geekMole | 来源:发表于2019-01-20 16:21 被阅读5次

    1. js深拷贝

    js深拷贝简单对象的拷贝可以用JSON.stringify() 和 JSON.parse() 实现, 但是如果想要正确拷贝方法和原型就需要遍历对象, 用ES6语法实现方法如下:

    let FengUtil = (()=> {
    
        /**
         * 获取obj的类型返回值首字母为大写
         * @param {*} obj 
         */
        let getType = (obj)=> {
            let type = Object.prototype.toString.call(obj);
            return /object\s(.*)]/.exec(type)[1];
        };
    
        /**
         * 判断对象是否为 type 类型
         * @param {*} obj 
         * @param {*} type 小写
         */
        let isType = (obj, type)=>{
            obj = getType(obj).toLowerCase();
            return obj === type;
        };
    
        /**
         * 深拷贝obj对象包括方法, 注意箭头函数内的this指针无法正确拷贝
         * @param {*} obj 
         */
        let deepCopy = (obj) => {
            // 若不是对象类型或是null对象,直接输出
            if (typeof obj !== 'object' || obj === null) {
                return obj
            }
        
            // 根据obj原型创建新对象
            let target = Object.create(obj);
            // 根据类型递归copy属性到新对象
            for (let i in obj) {
                if (typeof obj[i] === 'object') {
                    target[i] = deepCopy(obj[i]);
                }else if (typeof obj[i] === 'function') {
                    // function 类型不用拷贝
                    continue;
                } else {
                    target[i] = obj[i];
                }
            }
            return target;
        };
    
        return {
            getType: getType,
            isType: isType,
            deepCopy: deepCopy
        }
    
    })();
    

    经测试发现箭头函数内的this指针无法正确copy
    测试方法如下:

    class Person {
        constructor() {
            this.name = 'defaultName';
            this.age = 0;
            this.children = [{name: 'kindy', age:8}, {name:'bily', age:10}];
    
        }
    
        speak() {
            console.log('I am ' + this.name + ', I am speaking.');
        };
        repeat() {
            console.log('I am ' + this.name + ', I am repeating.');
        };
    }
    
    class Workman extends Person {
        constructor() {
            super();
            this.job = 'defaultJob';
        
            this.arrowFunc = () => {
                console.log('arrow func invorked');
            }
        
            this.work = () => {
                console.log('Infact I am ' + this.name);
                this.speak();
                console.log('I am working.');
            };
    
        }
        walk() {
            console.log('Infact I am ' + this.name);
            this.repeat();
            console.log('I am walking');
        }
    }
    
    const worker1 = new Workman();
    const child = new Workman();
    child.name = 'lilei';
    worker1.children.push(child);
    
    const worker2 = FengUtil.deepCopy(worker1);
    console.log('******测试对对象原型拷贝******');
    console.log(worker1.__proto__);
    console.log(worker2.__proto__);
    
    // 改变拷贝对象的属性和源对象属性
    worker1.name = 'worker1';
    worker2.name = 'worker2';
    
    console.log('******测试对方法和箭头函数拷贝******');
    console.log(worker2);
    worker2.work();
    worker2.walk();
    
    console.log('******测试对象型属性拷贝******');
    const childOf1 = worker1.children[2];
    childOf1.name = 'modifiedName';
    console.log(childOf1);
    const childOf2 = worker2.children[2];
    console.log(childOf2);
    

    附另外一种深拷贝方法, 缺点是无法实现对原型的拷贝, 另外对方法拷贝存在问题

    /**
     * 将obj对象传入,return一个复制后的对象出来
     * @param {*} obj
     */
    let deepCopy_other = (obj) => {
    
        // 若不是对象类型或是null类型,直接输出
        if (typeof obj !== 'object' || obj === null) {
            return obj
        }
    
        let i;
        // 根据目标是Array类型还是object来设置目标参数的类型
        let target = FengUtil.isType(obj, 'array') ? [] : {};
        for (i in obj) {
            // 判断当前复制的对象是否为对象类型数据
            if (typeof obj[i] === 'object') {
                deepCopy(obj[i]); // has bug of this line
            }
            target[i] = obj[i]
        }
        return target
    };
    

    2. js数据类型总结

    ********typeof********
    [] is: object
    {} is: object
    null is: object
    undefined is:undefined
    "str" is: string
    1 is: number
    1.1 is: number
    ********FengUtil.getType********
    [] is: Array
    {} is: Object
    undefined is:Null
    "str" is: Undefined
    "str" is: String
    1 is: Number
    1.1 is: Number
    

    相关文章

      网友评论

          本文标题:JS工具-类型判断和深拷贝

          本文链接:https://www.haomeiwen.com/subject/ogvxjqtx.html