Understanding the difference between Object.create() and new SomeFunction()

后端 未结 11 2488
失恋的感觉
失恋的感觉 2020-11-22 05:05

I recently stumbled upon the Object.create() method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with

11条回答
  •  渐次进展
    2020-11-22 05:50

    Object.create(Constructor.prototype) is the part of new Constructor

    this is new Constructor implementation

    // 1. define constructor function
    
          function myConstructor(name, age) {
            this.name = name;
            this.age = age;
          }
          myConstructor.prototype.greet = function(){
            console.log(this.name, this.age)
          };
    
    // 2. new operator implementation
    
          let newOperatorWithConstructor = function(name, age) {
            const newInstance = new Object(); // empty object
            Object.setPrototypeOf(newInstance, myConstructor.prototype); // set prototype
    
            const bindedConstructor = myConstructor.bind(newInstance); // this binding
            bindedConstructor(name, age); // execute binded constructor function
    
            return newInstance; // return instance
          };
    
    // 3. produce new instance
    
          const instance = new myConstructor("jun", 28);
          const instance2 = newOperatorWithConstructor("jun", 28);
          console.log(instance);
          console.log(instance2);
          
    

    new Constructor implementation contains Object.create method

          newOperatorWithConstructor = function(name, age) {
            const newInstance = Object.create(myConstructor.prototype); // empty object, prototype chaining
    
            const bindedConstructor = myConstructor.bind(newInstance); // this binding
            bindedConstructor(name, age); // execute binded constructor function
    
            return newInstance; // return instance
          };
    
          console.log(newOperatorWithConstructor("jun", 28));
    

提交回复
热议问题