Friday, June 15, 2018

JavaScript - Object Creation - Techniques - 2 - using object Function

Below code demonstrates the technique of creating object using function constructor:


//blueprint object
function Person(){
  this.name = "Cassandra"; // this sets to the object itself 
  this.age = 27;
  this.greet = function () {
    console.log("Hello, I am "+this.name);
  };
}

Person.prototype.name = "Sandra";

Person.prototype.greetGeneral = function(){
  console.log("Hello "+"there!");
}

// instance of the blueprint object 
var person = new Person();
person.name = "Andra";
Person.prototype.name = "Sandra"; // this does not override
// as it sets at a higher level - at prototype level
// instead of setting it at object level 

person.greet();

console.log(Person);
console.log(person.__proto__ == Person.prototype);
// We did not create Person1.prototype. JavaScript has created it for us
// The function here is a constructor function
// it is a normal function, but we use it as a constructor function 
// by adding a new keyword here
console.log(person.__proto__ );

var person2 = new Person();
console.log(person2.greetGeneral());

Refer:



Practice at:
http://jsbin.com

No comments:

Post a Comment