Most object-oriented languages can be used in a non-OO way. (Most non-OO languages can be used in an OO way as well, come to that, you just have to make an effort.) JavaScript is particularly suited to being used in both procedural and functional ways (and is also very well-suited to being used in various OO ways). It's a very, very flexible language.
For instance, here are two ways to write something that needs to deal with information about people, saying how old they are:
Procedural:
// Setup
function showAge(person) {
var now = new Date();
var years = now.getFullYear() - person.born.getFullYear();
if (person.born.getMonth() < now.getMonth()) {
--years;
}
// (the calculation is not robust, it would also need to check the
// day if the months matched -- but that's not the point of the example)
console.log(person.name + " is " + years);
}
// Usage
var people = [
{name: "Joe", born: new Date(1974, 2, 3)},
{name: "Mary", born: new Date(1966, 5, 14)},
{name: "Mohammed", born: new Date(1982, 11, 3)}
];
showAge(people[1]); // "Mary is 46"
This is not especially object-oriented. The showAge
function acts on objects given to it, assuming it knows the names of their properties. It's a bit like a C program working on struct
s.
Here's the same thing in an OO form:
// Setup
function Person(name, born) {
this.name = name;
this.born = new Date(born.getTime());
}
Person.prototype.showAge = function() {
var now = new Date();
var years = now.getFullYear() - this.born.getFullYear();
if (this.born.getMonth() > now.getMonth()) {
--years;
}
// (the calculation is not robust, it would also need to check the
// day if the months matched -- but that's not the point of the example)
console.log(person.name + " is " + years);
};
// Usage
var people = [
new Person("Joe", new Date(1974, 2, 3)),
new Person("Mary", new Date(1966, 5, 14)),
new Person("Mohammed", new Date(1982, 11, 3))
];
people[1].showAge(); // "Mary is 46"
This is more object-oriented. Both the data and behavior are defined by the Person
constructor function. If you wanted, you could even encapsulate (say) the born
value such that it couldn't be accessed from other code. (JavaScript is "okay" at encapsulation at the moment [using doing it with closures]; it will be getting a lot better at encapsulation [in two related ways] in the next version.)