Used to make a class from which to build instances.
function Animal (name, length) {
this.name = name;
this.length = length;
}another way to write this:
var Animal = function (name, length) {
this.name = name;
this.length = length;
}var animals = [
new Animal("Human", 2),
new Animal("Monkey", 2),
new Animal("Kangaroo", 2),
new Animal("Horse", 4),
new Animal("Cow", 4),
new Animal("Centipede", 100)
];
animals[2].name // "Kangaroo"Creates a class-like method.
Animal.prototype.identify = function() {
return "I am a " + this.name + " with " + this.length + " legs."
}
animals[0].identify() // "I am a Human with 2 legs."
animals[0].identify === animals[5].identify // true, only one implementation of the identify() function should existCreates a class object which can never create instances.
var Zoo = {
collection : [],
init : function(arr_of_animals) { this.collection = arr_of_animals },
bipeds : function () {
collect = []
for(var i = 0; i < this.collection.length; i++) {
if(this.collection[i].length == 2) {
collect.push(this.collection[i]);
}
}
return collect;
},
quadrupeds : function () {
collect = []
for(var i = 0; i < this.collection.length; i++) {
if(this.collection[i].length == 4) {
collect.push(this.collection[i]);
}
}
return collect;
}
}Zoo.init(animals);
Zoo.bipeds().length // 3
Zoo.quadrupeds().length // 2