About JS prototype syntax

Time:2022-3-13
  • Prototype grammar

    function Student(name,id){
                this.name = name;
                this.id = id;
            }
    
            //Gets the prototype of the object
            Student.prototype.type = "student";
            Student.prototype.message = function(){
                console.log(this.name + "," + this.id);
            };
            //Generate instance object
            var student1 = new Student("li",111);

    Directly use an object literal to assign a value to the prototype object

    Student.prototype = {
         type : "student",
         message : function(){
             console.log(this.name + "," + this.id);
         }
    };
    //It can be called normally
    student1.message();

    But one thing to note,student1.constructorThe direction of has changed because the prototype of student has been reset and the direction of constructor cannot be found,student1.constructorThe value of becomes object.

    To solve this problem, it is very simple to giveStudent.prototrpeWhen assigning a literal object of, you need to manually point the constructor attribute to the correct constructor.

    Constructor: student // the constructor is student
    • When defining constructors, when using prototype objects, it is recommended to set them in the following two ways according to the functions of members:

      ① Private members, generally non function members, are placed in the constructor;

      ② Shared members, generally functions, are placed in prototype objects;

      When you reset the prototype, remember to correct the direction of the constructor

  • Prototype object of JS native constructor

    • All functions have a prototype attribute object

      The built-in constructor in JavaScript also has prototype object properties:

          - Object.prototype

          - Function.prototype

          - Array.prototype

          - String.pprototype

          - Number.protoptype
          ……

      • Prototype method of expanding array

        Adding an object literal value directly to the prototype object is not enough. The built-in constructor has its protection mechanism (so the following code is not allowed).

        Array.prototype = {
            getSum = function(){
                 var sum = 0;
                 for(var i = 0;i < this.length;i++){
                    sum += this[i];
                 }
                 return sum;
            }  
        };
        console.dir(Array.prototype);

        Directly use array to call prototype to add new attributes

        Array.prototype.getSum = function(){
               var sum = 0;
                 for(var i = 0;i < this.length;i++){
                    sum += this[i];
                 }
                 return sum;
        };
        console.dir(Array.prototype);

        In actual development, it is not allowed to change JS native built-in objects.