·  JavaScript – Syntax – Terms – Methods

 

- Info:

  - It is inefficient to define methods as ordinary properties because each object will have its own copies of all properties.

  - This inludes complete copies of function properties too.

  - And since these function are supposed to be the same for all of the object of the same class it makes no sense to have

    exactly the same copy of a function in each created object.

 

  - Each JavaScript object has an internal reference to another object called prototype object.

  - Each JavaScript object inherits properties from its prototype object.

 

  - All functions have property with name prototype that is automaticly created and initizalized when fnction is defined.

  - Its value is object with a single property called construct.

  - This construct refers to constructor function.

  - Any properties you add to this object will appear as properties of objects initialized by this constructor.

  - Prototype object should hold properties and method which should be shared by all objects.

    So that they are not coped for each new object.

    This is equivalent to static properties in other OOP, they are shared by all objecs of the class.

    Difference is that in normat OOP languages this sharing is automatic for all methods too, they are always class bound.

 

    <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); }

        this.__proto__.hello = function() { console.log(this.name + " says hello."); }

      }

      

      //ADD METHOD AS PROPERTY TO PROTOYPE OBJECT.

      Person.prototype.hello = function() { console.log(this.name + " says hello."); }

     

      //CREATE OBJECT OF CLASS PERSON.

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

      

      //USE OBJECT.

      person1.say(); 

      person1.hello();

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

      console.log(person1);

   

    </script>