Object.create

What is Object.create?

A way to set the \__proto___ property of an object when we create it.

function Person(name) {
    this.name = name;
}

Person.prototype.sayHi = function() { 
   console.log("Hey" + this.name);
}

var person1 = new Person("Ian");
person1.sayHi(); -> Hey Ian

var person2 = Object.create(Person.prototype); 
person2.sayHi(); -> Hey Undefined 

//Why is it undefined? In Object.create(), the constructor was never called. 
//We need to do: 

var person2 = Object.create(Person.prototype); 
Person.call(person2, "Ian");  //This invokes the constructor function 
person2.sayHi(); -> Hey Ian

results matching ""

    No results matching ""