Showing posts with label Prototypes. Show all posts
Showing posts with label Prototypes. Show all posts

Sunday, December 16, 2018

JavaScript Objects Types


In JavaScript there are 3 ways you can create an Object. Examples as below,

var object1 =
{
    name: "Zack",
    age: 35
}

console.log("Object 1 Name: "+object1.name);

var object2 = new Object();
object2.name = "Zack";
object2.age = 35;

console.log("Object 2 Name: "+object2.name);

function Object3(name, age)
{
    this.name = name;
    this.age = age;
    this.getName =function () {
        return this.name;
    }
}
var object3 = new Object3("Zack", 35)
console.log("Object 3 Name: "+object3.getName());

object1.sex = "male";
object2.sex = "male";
Object3.sex = "male";// Value will be undefined for the Object
//Object3.prototype.sex = "male";

console.log("Object 1: "+ object1.sex);
console.log("Object 2: "+ object2.sex);
console.log("Object 3: "+ object3.sex);

The 3rd Type of Object is the most used type, since it is highly reusable.