目录
  • JavaScript的Object.create()方法
  • JavaScript手写Object.create函数
    • 函数功能
  • 总结

    JavaScript的Object.create()方法

    ES5定义了一个名为Object.create()的方法,它创建一个对象,其中第一个参数就是这个对象的原型,Object.create()提供第二个可选参数,用以对对象的属性进行进一步描述。

    // Object.create()是一个静态方法
    // 以下展示不同参数的用法
    
    // 一个参数
    var o = Object.create(null) // 相当于空对象,任何属性都没有
    var o = Object.create(Object.prototype) // 相当于var o = {}
    var o = Object.create({x: 1, y: 2}) // 相当于var o = {}; o.prototype = {x: 1, y: 2}
    
    // 第二个参数是一个对象,用于给创建的对象添加属性和属性描述的
    // 属性又分为数据属性和存取器属性
    // 数据属性的描述符对象的属性有value(值)、writable(可写性)、enumerable(可枚举性)、configurable(可配置性)
    // 存取器属性的描述符对象的属性有get(读取)、set(写入)、enumerable(可枚举性)、configurable(可配置性)
    
    // 两个参数
    var o = Object.create({x: 1, y: 2}, {
       a: {
       		value: 100,
       		......
       }
    }) // 向创建的对象o添加一个数据属性a,值为100,其它描述属性默认为false
    
    var o = Object.create({x: 1, y: 2}, {
       a: {
       		get() {
       			return this.x + this.y
       		},
       		......
       	}
    }) // 向创建的对象o添加一个存取器属性a,o.a时执行其get方法,set属性默认为undefined,其余描述属性默认为false
    

    JavaScript手写Object.create函数

    给大家分享一下手写 Object.create 函数。

    函数功能

    Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__

    代码:

    function create(parentPrototype, props) {
      function Fn() {
     
      }
      Fn.prototype = parentPrototype;
      let fn = new Fn();
      for (let key in props) {
        Object.defineProperty(fn, key, {
          enumerable: true, // 如果不枚举对象中无法查看到这个对象
          ...props[key]
        })
      }
      return fn
    }
     
     
    function Parent() {
      this.name = "parent";
    }
     
    Parent.prototype.eat = function () {
      console.log("eat");
    };
     
    function Child() {
      this.age = 9;
      Parent.call(this);
    }
     
    Child.prototype = create(Parent.prototype, { constructor: { value: Child } });
     
    // { constructor: { value: Child } }  这段代码保证 Child 的 prototype 的 constructor 还指向 Child 的构造函数
     
    let child = new Child();
    console.log(child.constructor,'constructor'); // [Function: Child] 'constructor'
    child.eat() // eat

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。