·  JavaScript – Syntax – Terms – Inheritance

 

- Info:

  - JavaScript was not designed to be Object Oriented.

  - Such behaviour is therefore emulated in aquard and complex way by using constructor functions and prototypes.

  - In JavaSript object is just hash, collection of key-value pairs where value can also be a function.

  - Problem is that these properties are always copied into newly created object.

  - So in case of methods each object holds it's own copy of the same method which takes a lot of resources.

  - Now instead of having simple keyword like static to indicate properties which should be shared by all objects instead of

    being copied into each one, you have to work with complex mess of using prototypes.

  - To have shared properties, which are not copied into every object, you have to put them into prototype object.

 

- Example:

  - This example tries to emulate class based behaviour.

  - Create D\Temp\JavaScript\Test.html

 

    Test.html

    <script> 

   

      //CONSTRUCTOR FOR CREATING OBJECTS OF CLASS PERSON.

      function Person(name, age) {

        this.name          = name;

        this.age           = age;

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

      }

      

      //CONSTRUCTOR FOR CREATING OBJECTS OF CLASS CHILD. 

      function Child(school, name, age) {

        this.school    = school;

        this.__proto__ = new Person(name, age);    //Inherit from object Person.

      }

      

      //CREATE CHILD OBJECT.

      john = new Child("3rd grade", "John", 12);

      john.say();

      console.log(john);

   

    </script>