Object Literals
const gabor = {
name: 'Gabor',
age: 36
}
console.log(gabor.name +' '+ gabor.age);
Constructor method
Person constructor with two property name and age
function Person(name, age){
this.name = name;
this.age = age;
console.log(this);
}
const gabor = new Person('Gabor', 36);
const john = new Person('John', 40);
Object { name: "Gabor", age: 36 }
Object { name: "John", age: 40 }
Calculate age
function Person(name, dob){
this.name = name;
this.birthday = new Date(dob);
this.calculateAge = function(){
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
}
const gabor = new Person('Gabor', '1984-11-24');
console.log(gabor.calculateAge());
Leave a Reply