Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • JavaScript - Get Started
  • What is JavaScript
  • Setup JavaScript Dev Environment
  • HTML <script> Tag
  • JavaScript - Syntax
  • JavaScript - Popup Message
  • JavaScript - Variables
  • JavaScript - Operators
  • JavaScript - Data Types
  • JavaScript - String
  • JavaScript - Numbers
  • JavaScript - Boolean
  • JavaScript - Object
  • JavaScript - Date
  • JavaScript - Date Methods
  • JavaScript - Array
  • JavaScript - Array Methods
  • JavaScript - null and undefined
  • JavaScript - Function
  • JavaScript - if condition
  • JavaScript - switch
  • JavaScript - for loop
  • JavaScript - while loop
  • JavaScript - Scope
  • JavaScript - eval
  • JavaScript - Error Handling
  • JavaScript - strict mode
  • JavaScript - Hoisting
  • Define JS Class
  • JS Object In Depth
  • this Keyword
  • new Keyword
  • Prototype
  • Inheritance
  • Closure
  • IIFE
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Define Class in JavaScript

JavaScript ECMAScript 5, does not have class type. So it does not support full object oriented programming concept as other languages like Java or C#. However, you can create a function in such a way so that it will act as a class.

The following example demonstrates how a function can be used like a class in JavaScript.

Example: Class in JavaScript
function Person() {
    this.firstName = "unknown";
    this.lastName = "unknown";
}

var person1 = new Person();
person1.firstName = "Steve";
person1.lastName = "Jobs";
            
alert(person1.firstName + " " + person1.lastName);

var person2 = new Person();
person2.firstName = "Bill";
person2.lastName = "Gates";
            
alert(person2.firstName + " " + person2.lastName );
Try it

In the above example, a Person() function includes firstName, lastName & age variables using this keyword. These variables will act like properties. As you know, we can create an object of any function using new keyword, so person1 object is created with new keyword. So now, Person will act as a class and person1 & person2 will be its objects (instances). Each object will hold their values separately because all the variables are defined with this keyword which binds them to particular object when we create an object using new keyword.

So this is how a function can be used like a class in the JavaScript.

Add Methods in a Class

We can add a function expression as a member variable in a function in JavaScript. This function expression will act like a method of class.

Example: Method in Class
function Person() {
            this.firstName = "unknown";
            this.lastName = "unknown";
            this.getFullName = function(){
                return this.firstName + " " + this.lastName;
            }
        };

var person1 = new Person();
person1.firstName = "Steve";
person1.lastName = "Jobs";

alert(person1.getFullName());
     
var person2 = new Person();
person2.firstName = "Bill";
person2.lastName = "Gates";

alert(person2.getFullName());
Try it

In the above example, the Person function includes function expression that is assigned to a member variable getFullName. So now, getFullName() will act like a method of the Person class. It can be called using dot notation e.g. person1.getFullName().

Constructor

In the other programming languages like Java or C#, a class can have one or more constructors. In JavaScript, a function can have one or more parameters. So, a function with one or more parameters can be used like a constructor where you can pass parameter values at the time or creating an object with new keyword.

Example: Constructor
function Person(FirstName, LastName, Age) {
        this.firstName = FirstName || "unknown";
        this.lastName = LastName || "unknown";
        this.age = Age || 25;
        this.getFullName = function () {
            return this.firstName + " " + this.lastName;
        }
};

var person1 = new Person("James","Bond",50);
alert(person1.getFullName());

var person2 = new Person("Tom","Paul");
alert(person2.getFullName());
Try it

In the above example, the Person function includes three parameters FirstName, LastName and Age. These parameters are used to set the values of a respective property.

Please notice that parameter assigned to a property, if parameter value is not passed while creating an object using new then they will be undefined.

Properties with Getters and Setters

As you learned in the previous section, Object.defineProperty() method can be used to define a property with getter & setter.

The following example shows how to create a property with getter & setter.

Example: Property
function Person() {
    var _firstName = "unknown";

    Object.defineProperties(this, {
        "FirstName": {
            get: function () {
                return _firstName;
            },
            set: function (value) {
                _firstName = value;
            }
        }
    });
};

var person1 = new Person();
person1.FirstName = "Steve";
alert(person1.FirstName );
            
var person2 = new Person();
person2.FirstName = "Bill";
alert(person2.FirstName );
Try it

In the above example, the Person() function creates a FirstName property by using Object.defineProperties() method. The first argument is this, which binds FirstName property to calling object. Second argument is an object that includes list of properties to be created. We have specified FirstName property with get & set function. You can then use this property using dot notation as shown above.

Read-only Property

Do not specify set function in order to create read-only property as shown below.

Example: Read-only Property
function Person(firstName) {

    var _firstName = firstName || "unknown";

        Object.defineProperties(this, {
            "FirstName": {
                get: function () {
                    return _firstName;
                }
            }
        });
    };
var person1 = new Person("Steve");
//person1.FirstName = "Steve"; -- will not work
alert(person1.FirstName );
            
var person2 = new Person("Bill");
//person2.FirstName = "Bill"; -- will not work
alert(person2.FirstName );
Try it

Multiple Properties

Specify more than one property in defineProperties() method as shown below.

Example: Multiple Properties
function Person(firstName, lastName, age) {
    var _firstName = firstName || "unknown";
    var _lastName = lastName || "unknown";
    var _age = age || 25;

    Object.defineProperties(this, {
        "FirstName": {
            get: function () { return _firstName },
            set: function (value) { _firstName = value }
        },
        "LastName": {
            get: function () { return _lastName },
            set: function (value) { _lastName = value }
        },
        "Age": {
            get: function () { return _age },
            set: function (value) { _age = value }
        }
    });

    this.getFullName = function () {
            return this.FirstName + " " + this.LastName;
    }
};

var person1 = new Person();
person1.FirstName = "John";
person1.LastName = "Bond";
    
alert(person1.getFullName());
Try it
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.