Simple JavaScript Object and Class Examples

In JavaScript, most things are objects. An object is a collection of related data and/or functionality

Namespace: Everything you create in JavaScript is by default global. In JavaScript namespace is Global object.
How to create a namespace in JavaScript?
Create one global object, and all variables, methods, and functions become properties of that object.
// global namespace
var MYAPP = MYAPP || {};
Explaination: Here we first checked whether MYAPP is already defined.If yes, then use the existing MYAPP global object, otherwise create an empty object called MYAPP

How to create sub namespaces?
// sub namespace
MYAPP.event = {};

JavaScript is a prototype-based language and contains no class statement.JavaScript classes create simple objects and deal with inheritance.

var Person = function () {};
Explaination: Here we define a new class called Person with an empty constructor.

Use the class keyword
class Calculation {};
A class expression is another way to define a class. Class expressions can be named or unnamed.
// unnamed
var Calculation = class {};

// named
var Calculation = class Calculation { };

Function based classes

function Calculation() { }
// associate method to class
Calculation.prototype.square = function() {
  return this;
Calculation.cube = function() {
  return this;

let obj = new Calculation();
let square = obj.square;
square(); // global object

let cube = Calculation.cube;
cube(); // global object

Sub classing with extends
class Teacher { 
  constructor(name) { = name;
  attendance() {
    console.log( + ' teacher present.');

class Student extends Teacher {
  attendance() {
    console.log( + ' student present.');

var d = new Student('Sudhir');
d.attendance(); // Sudhir student present.

JavaScript object
A JavaScript object is a collection of named values
var address = {city:"Noida", state:"Uttar Pradesh", country:"India"};
To access city use :;

Or you can create using new keyword

var address = new Object(); = "Noida";
address.state = "Uttar Pradesh"; = "India";

Note:JavaScript objects are mutable.Any changes to a copy of an object will also change the original.Every object in JavaScript is an instance of the object Object and therefore inherits all its properties and methods.
var address = {city:"Noida", state:"Uttar Pradesh", country:"India"}
var x = address;
x.state = "Delhi";
document.getElementById("demo").innerHTML = + " is " + address.state + " state.";

In JavaScript the function serves as the constructor of the object, therefore there is no need to explicitly define a constructor method.
var Person = function () {
  console.log('instance created');

var person1 = new Person();
function Person(name) { = name;
var thePerson = new Person('Redwood');
console.log('thePerson.constructor is ' + thePerson.constructor);

This example displays the following output:

thePerson.constructor is function Tree(name) { = name;

The methods
To define a method, assign a function to a named property of the class's prototype property.
var Person = function (firstName) {
  this.firstName = firstName;

Person.prototype.sayHello = function() {
  console.log("Hello, I'm " + this.firstName);
var person1 = new Person("Alice");

var helloFunction = person1.sayHello;;

For loop in JavaScript
var address = {fname:"Noida", state:"Uttar Pradesh", country:"India"}; 
for (x in address) {
txt += address[x];

JavaScript object method: 
var address = {
    city: "Noida",
    state:"Uttar Pradesh", 
   fullAddress : function() {
        return + " " + this.state + " " +;
address.fullAddress(); // returns fullAddress

JavaScript Prototypes
A prototype is an object from which other objects inherit properties.Every object has a prototype by default.

Adding Methods to a Prototype
function Address(city, state) { = city;
     this.state = last;
     this.cityState = function() {
         return + " " + this.state

Address.prototype.location = function() {

var myAddress = new Address("Noida", "Delhi");
myAddress.location(); // It will return Noida Delhi

Using the prototype Property

JavaScript prototype property allows you to add new properties to an existing prototype
Example: Address.prototype.nationality = "English";

Place the javascript function inside a variable
var consoleOutput = function consoleOutput()
console.log('Hello Sudhir');

Bind a function with event javascript
document.getElementsByClassName("inner-heading")[0].addEventListener("click", consoleOutput);

Same thing can be done by using jquery

Lets us take real example for bootstrap notification
var flashMessage;
flashMessage = flashMessage || (function(){
var loadingDiv = $('<div id="myModal" class="modal fade" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><i class="fa fa-spin fa-spinner fa-5x"></i></div></div></div></div>');
return {
showPleaseWait: function() {
loadingDiv.on('', function(){
hidePleaseWait: function () {
if ($('section').hasClass('_alertDialog')) {
if(type == 'success'){
_curAlertClass = 'alert-success';
_curAlertIcon = 'fa-check';
_curAlertClass = 'alert-danger';
_curAlertIcon = 'fa-warning';

var _dialogContainer = $('<section class="content _alertDialog" style="display:none;"></section>');
var _ele = $('<div class="alert '+ _curAlertClass +' alert-dismissable"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a><div class="alert-message"><i class="fa '+_curAlertIcon+'"></i> '+msg+'</div></div>');
var _timerId = setTimeout(function() { _dialogContainer.slideUp( 300 ); clearTimeout(_timerId); }, 5000);

Now How to access its function

flashMessage.alertMessageBox('<p>This is testing javascript object</p>', 'success');


  1. very useful info, and please keep updating........
    Best Online Software


    1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.

      Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.

      Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

      The Nodejs Projects Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

  2. This is an amazing blog,it gives very helpful messages to us.Besides that Wisen has established as Best Javascript Training in Chennai . or learn thru JavaScript Online Training India. Nowadays JavaScript has tons of job opportunities on various vertical industry.

  3. Sap Training Institute in Noida-Webtrackker is the best SAP training institute in noida. SAP is drastically a completely state-of-the-art element ever to analyze and to excel in it. However with the ever-growing price, and being the most accessible organization solution key, agencies are greater involved to have their employees specialized in it. The education courses effectively deliver you with the fundamental recognition of SAP, in a grade by grade way.
    Sas Training Institute in Noida
    PHP Training Institute in Noida
    Hadoop Training Institute in Noida
    Oracle Training Institute in Noida
    Linux Training Institute in Noida
    Dot net Training Institute in Noida

  4. This comment has been removed by the author.

  5. Australia best tutor is well known academic portal. Here students can get different kind of Online Assignment help services like that

    1.Online Assignment Help
    2.Instant Assignment Help
    3.Assignment Help
    4.Help with Assignment assignment Help

    And also access that services at any time and any where.

  6. Air conditioning maintenance birmingham- onlyrepaircenter has the 30 Years Experience in Air conditioning maintenance service in birmingham. If you are facing the problem in your air conditioning of any company such as Daikin, Mitsubishi, Carrier, Fujitsu, Toshiba, Airedale, Sanyo, Trane and LG then you can contact to us.

    Air Conditioning Installation birmingham
    Commercial air conditioning repair Birmingham
    residential air conditioning repair birmingham
    Air Conditioning Maintenance birmingham
    window ac repair birmingham

  7. I can only express a word of thanks! Nothing else. Because your topic is nice, you can add knowledge. Thank you very much for sharing this information.

    Avriq India
    pest control
    cctv camera

  8. CIIT Noida provides Best MCA Courses in Noida based on the current IT industry standards that help students to get high paying jobs in Top MNCs. CIIT provides Best MCA Training in Noida, Greater Noida, and Ghaziabad. CIIT is one of the trusted MCA training institutes in Noida providing practical knowledge and 100% job assistance with basic as well as advanced level MCA subjects. CIITN is the best MCA college in Noida, greater noida, ghaziabad, delhi, gurgaon regoin.

    At CIIT MCA classes in Noida is conducted by subject experts corporate professionals with 9+ years of experience in managing real-time and live projects. Sofracle Nano Specialized MCA classes Noida is the perfect blend of academic learning and practical sessions to provide maximum exposure to students that transform an average student into a corporate professional whom companies prefer to hire.

    Best MCA College in Noida

  9. To improve Knowledge about the latest and vital technology would increase one's self esteem to the core at the time of lagging confidence.The content presented here is quite resembling the same. You have done a great job by sharing this in here.
    sap abap training online

  10. Thank you for this post. Thats all I are able to say. You most absolutely have built this blog website into something speciel. You clearly know what you are working on, youve insured so many corners.thanks

    Selenium training in Chennai

    Selenium training in Bangalore

  11. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing..
    Believe me I did wrote an post about tutorials for beginners with reference of your blog. 

    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

  12. This comment has been removed by the author.

  13. Want to play at the most popular online casino? Then come to us and abrai your winnings as soon as possible. excellent online slot machines Come in and try your luck.

  14. This comment has been removed by the author.

  15. Amazing post. I really enjoy for this status.
    This post are very useful and powerful . Your services are best.
    Thanks for sharing..Study in Canada Consultants
    study in Canada consultansts in Delhi
    canada immigration consultants in delhi

  16. This comment has been removed by the author.

  17. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.
    data science training in indore

  18. Thanks for posting such a Useful information .You have done a great job.
    Online Training
    software training institute
    online classes

  19. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    splunk online training

  20. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angular js online training
    best angular js online training
    top angular js online training

  21. Thanks for sharing a very useful article. Am sure it helped to clear the doubts I had. Keep posting more. Also dont forget to check out our pages too.

    data science training in chennai

    ccna training in chennai

    iot training in chennai

    cyber security training in chennai

    ethical hacking training in chennai

  22. Your content is very unique and understandable useful for the readers keep update more article like this.
    data science course in gurgaon



  24. I simply stumbled upon your weblog and desired to say that I have really enjoyed surfing your blog articles.
    Positive site, where did u come up with the info on this uploading?
    yorkie puppies for sale
    teacup yorkie puppies for sale
    yorkies for sale
    yorkie for sale
    yorkshire terrier for sale
    yorkie puppy for sale
    teacup yorkies for sale
    teacup yorkie for sale
    yorkie teacup for sale

  25. Heya i'm for the first time here. I came across this board and I find
    It truly useful & it helped me out much. I hope to give something back
    and help others like you aided me.
    yorkies for sale near me
    yorkie for sale near me
    yorkie puppies near me
    yorkies near me
    yorkshire terrier for sale
    yorkie puppy for sale near me
    yorkie puppies for sale near me
    teacup puppies for sale near me
    teacup yorkie for sale





  29. This post is very simple to read and appreciate without leaving any details out. Great work!
    data analytics training in aurangabad

  30. Windows 7 product keys for 64-bit version · MLPOK-NJIUH-BVGYT-FCXDR-ESZAQ · W1Q2A-3S4F4-R5TGY-HG7UH-Y8IKJ · M9N8B-7V6C5-X4Z32-SDA4D-EF5GH · T6HJY-67JKI-U789L-KMNBV- .Windows 7 Product Key Crack

  31. Synthesia Crack is a best tool to learn or play the piano in an advanced manner. It works like a real piano to provide you the full taste. File Magic License Key


Post a Comment