When working with objects that are primarily used as data containers without specific behaviors, using an object literal is a suitable approach.
var information = {
name: 'John',
age: 30
};
Following the KISS principle, simplicity is key. For basic data storage needs, stick to using object literals.
If you intend to incorporate behavior into your object, consider utilizing constructors or prototypes to add methods and functionality during the object's initialization.
function Person(name, age) {
this.name = name;
this.age = age;
this.checkAge = function () {
return this.age >= 18;
};
}
// or:
Person.prototype.checkAge = function () {
return this.age >= 18;
};
This class structure also serves as a blueprint for your data object, defining the properties it holds through the constructor. In contrast, a plain literal lacks this structured definition.
You could alternatively create an external checkAge
function to operate on a simple data object:
var info = {
name: 'Jane',
age: 25
};
function checkAge(data) {
return data.age >= 18;
}
Nevertheless, such an approach compromises encapsulation since ideally, data and its corresponding behavior should be contained within the same entity.