·  JavaScript – Syntax – Keywords – new

 

- Info:

  - new keyword is used to create objects.

 

- Additional Tutorials:

  - Inheritance

  - Methods

 

- Usage:

  - new operator must be followed by a function call.

  - new operator first creates new object, with no properties.

  - Then it calls the function passing the new object as the value of this keyword.

  - Function designed to be used with new keyword  is called constructor.

  - Constructor's job is to initialize newly created object, setting properties before the object is used.

  - After function ends newly created and initialized object is returned (if function has no return value).

  - Constructor can return object in which case it is that object that is returned instead of this object.

  - Constructor provides name for a class of objects.

 

    <script> 

   

      //CONSTRUCTOR FOR CREATING OBJECTS OF CLASS PERSON.

      function Person(name , age) {

        this.name = name;

        this.age  = age;

        this.say  = function() { console.log(this.name + " is " + this.age); }

      }

     

      //CREATE OBJECT OF CLASS PERSON.

      person1 = new Person("John", 50);

      

      //USE OBJECT.

      person1.say();

      console.log(person1.name + " is " + person1.age);

   

    </script>