new Operator
- This is used to create an object from a constructor function
- The
new
keywords also execute the constructor function
function Car() {
console.log(this) // this points to myCar
this.name = "Honda";
}
var myCar = Object.create(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
More JavaScript Lessons(from my blog):
Most Frequently Asked JavaScript Interview Questions
Super powerful JavaScript tips & tricks - Part 2
JavaScript Quiz: How well do you know JavaScript?
Top comments (1)
Thanks