Class by object literal
/*var Person1 = {
name: 'Person1',
age: 24,
greeting: function(){
//console.log("Hi my name is " + Person.name); //but this is better
console.log("Hi my name is " + this.name);
}
}
var Person2 = {
name: 'Person2',
age: 34,
greeting: function(){
//console.log("Hi my name is " + Person.name); //but this is better
console.log("Hi my name is " + this.name);
}
}
var Person3 = {
name: 'Person3',
age: 54,
greeting: function(){
//console.log("Hi my name is " + Person.name); //but this is better
console.log("Hi my name is " + this.name);
}
}*/
// Imagine we need 1000 Persons, we can't each time maintai such objects!!!
// So to simulate "class" we can create object to be prototype
var person = {
constructor: function(name, age){
this.name = name; // 'this' looks on object to which method belongs
this.age = age;
return this; //return object person
},
greeting: function(){
console.log("Hi my name is " + this.name + ' and my age is ' + this.age);
}
}
var Person1 = Object.create(person).constructor('Evgeni', 34);
console.log(Person1.greeting());
var Person2 = Object.create(person).constructor('Cion', 60);
console.log(Person2.greeting());
var Person3 = Object.create(person).constructor('Navit', 31);
console.log(Person3.greeting());