[JavaScript] Classes
category: Website | course: JavaScript | difficulty:Now that we’ve learned about objects and scope, we can finally piece them together to create the building blocks of most JavaScript programs: Classes. A class is a function that creates an object with predetermined properties, but dynamically generated values. Then you can call the function, supply the right arguments, and you have a new, fully capable object.
Defining Classes
Classes are essentially just functions, which means it’s common practice to start them with a capital letter to distinguish them from non-class functions. Such a function is usually called a constructor function.
Within the function, we can use the this
keyword to refer to the object it will create, and define all its properties.
function Animal(name,type,age) { this.name = name; this.type = type; this.age = age; }
Creating Objects from Classes
For this we call the function, but with the new
keyword in front. This tells JavaScript that we want a new object created from the constructor function, and not just execute the function.
var newAnimal = new Animal("Debby","Cow",4);
Prototype
It’s great that we can create objects with methods included at the same time, but what if we want to add a method to all instances of this object later on? That’s when prototypes kick in! Every type of object has a prototype
, from which it inherits all properties and methods. We can access it using the dot notation we’re used to, and use it to add a new method.
var newAnim = new Animal("Laura"); Animal.prototype.changeName = function(a) { this.name = a } bla.changeName("Juan"); console.log(bla.name); //Prints "Juan"
The great thing about this, is that we can also add our own methods to JavaScript’s standard objects, like Math
or String
. For example, we could write a function that returns the amount of times a certain letter occurs within a string, add that to the prototype, and we’re able to perform this method on every string!
//This function accepts a one-character string, and counts how often it occurs in a string String.prototype.countThem = function(a) { var s = this; var count = 0; for(var i=0;i<s.length;i++) { if(s.charAt(i) == a) { count++; } } return count; } var x = "Hello World!".countThem("l"); //x is 3