JSFiddle - React, Tailwind, and code Playground
by theacadian
JavaScript
// class1 - Here we are declaring a "Object Literal", which is a comma-separated list of name-value pairs.
// Syntax -
// var obj_name = { prop1_name : prop1_value, prop2_name : prop2_value } ;
// We cannot use the 'new' operator to create 'instances' of class1
var class1 = {
showAlert1: function () {
alert("class1.showAlert1() called");
},
showAlert2: function () {
alert("class1.showAlert2() called");
}
};
class1.showAlert1();
class1.showAlert2();
/*
var obj1 = new class1(); // does not work
*/
// class2 - Below is a proper Constructor Function (or a Class definition in C#).
// In order to use the functions showAlert1() & showAlert2(), we have to use the 'new' operator to create an instance of class2, and only then can we access those functions
// Observe the 'this' keyword before the function names; 'this' refers to the instance that will be created using the 'new' operator
var class2 = function() {
this.showAlert1 = function () {
alert("class2.showAlert1() called");
};
this.showAlert2 = function () {
alert("class2.showAlert2() called");
};
};
/*
class2.showAlert1(); // does not work
class2.showAlert2(); // does not work
*/
var obj2 = new class2();
obj2.showAlert1();
obj2.showAlert2();