I am Hack Sparrow
Captain of the Internets.

How to create Class in JavaScript

Creating Classes in JavaScript

So you wanna learn how to create Classes in JavaScript. Heck, maybe you wanna know how to do object-oriented stuff in JavaScript! I plan to write an elaborate article on object-oriented JavaScript some day, but for now I will show you how to create a class in JavaScript.

You already must be familiar with JavaScript object instantiation a.k.a creation of a JavaScript objects. Like var d = new Date(), var a = new Array() etc. If you are not familiar with these code, you need to study more of and play around with JavaScript.

Do you wanna create your own JavaScript classes and do stuff like var m = new Monkey()? Creating a class called Monkey and instantiating Monkey objects. It is very simple to create classes in JavaScript - just define a well-named function, and you have your own class!

In the example below, we create a Monkey class, instantiate it, and then access its variables and methods.

function Monkey(type, name) {
var classname = 'monkey';
this.type = type;
this.name = name;
this.run = function () {
console.log(this.name + ' runs and runs!');
}
this.info = function () {
console.log(this.name + ' is a ' + this.type + ' ' + classname);
}
}

var m = new Monkey('capuchin', 'Jack');
console.log('The monkey is named ' + m.name);
console.log(m.run());
console.log(m.info());

All objects defined inside the function are properties of the class. Those attached to this are public properties and those defined with a var are private properties. Properties which are assigned to functions become the class methods and those assigned to variables become class variables. Savvy?

I am gonna be doing a very detailed article on Object-oriented JavaScript (OOJS) one of these days, more information awaits you there - in the future.

TLDR: Every function in JavaScript is a class, just instantiate it like how you would do for any other class. Eg: var f = new MyGoddamnFunction(). Make sure you have defined the function first and have created the necessary variables and functions in the class function.

Exercise

  1. What is the significance of 'a well-named function'?
  2. What does this refer to?
  3. What would happen if we don't pass the type and name parameters?
  4. What would this code do? console.log('Type: ' + m.classname)
  5. Is there any other way to create properties in a Class?

Make a Comment