Search

Class in JavaScript

As per Wikipedia: "JavaScript is classified as a prototype-based scripting language with dynamic typing and first-class functions. This mix of features makes it a multi-paradigm language, supporting object-oriented,[6] imperative, and functional[1][7] programming styles." But we still never explore the object orientation side of it, to start with.. we can create Class & Modules to divide the program in small chucks oflogic. This example shows you how to create a class in JavaScript.
/* Jscript */
/* Class in JavaScript */
var ClassName = (function () {
// Constructor
function ClassName(message) {
this.variable1 = message;
}
// Method
ClassName.prototype.greet = function () {
return "Hello, " + this.variable1;
};
return ClassName;
})();
var greeter = new ClassName("world");
view raw Class.js hosted with ❤ by GitHub
As per the above code, we have defined a class which is actually a function since JScript don't have class keyword and a constructor(will be same as the class name). "this" refers to the current object in memory and the variable1 is prototyped to it.