python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
associative arrays in JavaScript

How do you define a class and its constructor?

A JavaScript Constructor is a function which is used as a constructor that allows you to create an object from a class. A constructor access is one of public, protected and private.

Three ways to define a JavaScript class,
1.      Using as a function
2.      Using as Object Literals
3.      Singleton using as a function


The Syntax

access NameOfAClass(parameters) {
   initialization code;
}
//Access as public 
public customer(parameters) {
   initialization code;
}
//Access as protected 
protected customer(parameters) {
   initialization code;
}
//Access as private 
private customer(parameters) {
   initialization code;
}

Examples as,
//class declaration inJavaScript
//constructor
var customer = function (id, name, age) { }
customer.prototype = {}

//Instance variables members.
var customer = function (id, name, age) {
    this.id = id;
    this.name = name;
    this.age = age;
}
customer.prototype = {}


//Static variables.
var customer = function (id, name, age) {
    this.id = id;
    this.name = name;
    this.age = age;
}

customer.prototype = {
    staticVar1: 20,
    staticVar2: 'Anil'
}

//Instance functions methods.
var customer = function (id, name, age) {
    this.id = id;
    this.name = name;
    this.age = age;
}

customer.prototype = {
    getId: function () {
        return this.id;
    },

    setId: function (id) {
        this.id = id;
    }
}

//Static functions
var customer = function (Id, name, age) {
    this.id = id;
    this.name = name;
    this.age = age;
}

customer.create = function (Id, name, age) {
    return new customer(Id, name, age);
}
customer.prototype = {}

Stayed Informed - 39 Best Object Oriented JavaScript QA

What happens when a constructor is called?
1.      It creates a new object.
2.      It sets the constructor property of the object to Vehicle.
3.      It sets up the object to delegate to customer.prototype.
4.       It calls customer() in the context of the new object.

I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions