JS objects
by AlexMM
JavaScript
// 1-Constructor with JavaScript object literal
var person1 = {
firstName: 'Alex',
lastName: 'Moros',
birthYear: 1984,
getFullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
//Log values
console.log(person1.getFullName());
console.log(person1.birthYear);
// 2-Constructor with 'new Object()'
// This constructor is slower than literal one
var person2 = new Object();
person2.firstName = 'Alex';
person2.lastName = 'Moros';
person2.birthYear = 1984;
person2.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
//Log values
console.log(person2.getFullName());
console.log(person2.birthYear);
// 3-Constructor with an "object constructor function"
// It allows defining the parent/object prototype of the instance
function Person(first, last, bYear) {
this.firstName = first;
this.lastName = last;
this.birthYear = bYear;
}
Person.prototype.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
Person.MAX_ARMS = 2; // public static property
Person.MAX_LEGS = 2; // public static property
var person3 = new Person('Alex', 'Moros', 1984);
console.log(person3.getFullName());