Using “Object.create” instead of “new”

后端 未结 15 2149
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 06:08

Javascript 1.9.3 / ECMAScript 5 introduces Object.create, which Douglas Crockford amongst others has been advocating for a long time. How do I replace new

15条回答
  •  清酒与你
    2020-11-22 06:58

    new Operator

    • This is used to create object from a constructor function
    • The new keywords also executes the constructor function
    function Car() {
      console.log(this) // this points to myCar
      this.name = "Honda";
    }
    
    var myCar = new Car()
    console.log(myCar) // Car {name: "Honda", constructor: Object}
    console.log(myCar.name) // Honda
    console.log(myCar instanceof Car) // true
    console.log(myCar.constructor) // function Car() {}
    console.log(myCar.constructor === Car) // true
    console.log(typeof myCar) // object
    
    

    Object.create

    • You can also use Object.create to create a new object
    • But, it does not execute the constructor function
    • Object.create is used to create an object from another object
    const Car = {
      name: "Honda"
    }
    
    var myCar = Object.create(Car)
    console.log(myCar) // Object {}
    console.log(myCar.name) // Honda
    console.log(myCar instanceof Car) // ERROR
    console.log(myCar.constructor) // Anonymous function object
    console.log(myCar.constructor === Car) // false
    console.log(typeof myCar) // object
    
    

提交回复
热议问题