zoukankan      html  css  js  c++  java
  • Object.create实现类继承和克隆对象

    Object.create实现类继承

    先看不用Object.create来实现继承

    function Pd(){
    }
    Pd.prototype = Array.prototype;
    Pd.prototype.constructor = Pd;
    var pdd = new Pd();
    pdd.push(3);
    console.log(pdd); // Pd [3] __proto__:Array(0)直接就是真正的数组的__proto__
    

    效果:

    image.png

    用Object.create实现继承

    function Pd(){
    }
    Pd.prototype = Object.create(Array.prototype);
    Pd.prototype.constructor = Pd;
    var pdd = new Pd();
    pdd.push(3);
    console.log(pdd); // Pd [3] __proto__:Array[__proto__:Array(0)]就是__proto__里面包含真正的数组的__proto__
    

    效果:

    image.png

    区别

    写法

    Pd.prototype = Array.prototype;Pd.prototype = Object.create(Array.prototype);

    返回值

    • Pd [3] __proto__:Array(0)直接就是真正的数组的__proto__;
    • Pd [3] __proto__:Array[__proto__:Array(0)]就是__proto__里面包含真正的数组的__proto__

    用Object.create克隆对象

    var obj1 = {a:2,b:{name:'小明'}};
    var obj2 = Object.create(obj1);
    console.log(obj2); // {}
    obj2.a = 3;
    obj2.b.name = '小红';
    console.log(obj1); // {a:2,b:{name:'小红'}};
    

    结论:obj1对象中的一级对象a:2并没有受影响,但二级对象b已经受影响。所以Object.create克隆的对象也只能实现一级对象的深拷贝。

    obj2的具体值:

    image.png

  • 相关阅读:
    小伙子的毕业设计
    mongoDB
    Java面试题笔试题收集
    react-router4 介绍
    React 组件间通信 总结
    react ajax
    react应用(基于react脚手架)
    React 之 组件生命周期
    组件收集表单数据
    组件的组合使用
  • 原文地址:https://www.cnblogs.com/firefly-pengdan/p/13383986.html
Copyright © 2011-2022 走看看