Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Constructor and Object in JavaScript with example

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 363
    Comment on it

    Constructor, classes, and object are the foundation of OOPS language. In javascript, we also use constructor, classes, and object. I will explain this by using a simple example but before starting this we should know what is constructor, classes, and object

    Constructor:

    The constructor is called at the moment of instantiation. In other words, we can say that when we will create the object of any instance then constructor will call. In JavaScript the function serves as the constructor of the object, therefore, there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation.

     

    Object: An object is an instant of a class.

     

    So now I will write an example and then explain its working :

     

    //Create constructor
    var constructorFunction= function(message){
         this.message=message;
         this.hello=function(){
             console.log(this.message);
         }
    }
    //We also define constructor method explicitly like this
    
    constructorFunction.prototype.hello = function(){
        console.log(this.message);
    }
    
    //Now we will create object by using new keyword which will automatically call above constructor.
    
    var object=new constructorFunction('This is a example message');
    
    //Now I want to call message after every 4 second so for this I will use function setTimeout.
       setTimeout(function() {
              object.hello();
       }, 4000)

     

    In the above example, we can see that first we have created constructor implicitly and then explicitly by using the keyword prototype. then we have created the object of that instance . When we did that then the constructor is called automatically then I want to call message after every 4 seconds so I will use setTimeout function which will display our message at every 4 seconds.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: