A Brief discussion on static and prototype attributes of Javascript

  • 2020-06-07 04:00:25
  • OfStack

This article gives you an example of Javascript's static and prototype methods. If you are not familiar with Javascript's static and prototype methods, check out this site 1. 1 section of code to understand static methods and instance methods:


    <script>
    // Object constructor 
    function Atest(name){
      // A private property that can only be used inside an object constructor 
      var className = "Atest";
      // Public attribute , Called after the object is instantiated 
      this.name = name;
      // Object methods 
      this.hello = function(){
        alert(this.name);
        alert(this.msg());// Methods augmented with prototype methods can be used within a class 
        alert(this.sex);// Properties extended using the stereotype method can be used within a class 
        alert(Atest.age);// Static property calls are formatted as [ object . Static attributes ]
      }
    }
    // Class method  ( It's actually a static method that's called directly )  Location: Person Outside of a class   Syntax format: Class name . Method names  = function([ parameter ...]){  Statement line ; }
    Atest.Run = function(){
      alert(" I'm a class method  Run");
    }
 
 
    // Prototype method 
    Atest.prototype.msg = function(){
      alert(" My name is: "+this.name);// If the prototype method is called directly as a static method, this.name Cannot be called 
    }
 
    // Public static property   Outside of the class 
    Atest.age = 20;// Public static attributes cannot be used   【 this. Attribute, can only be used    【  object . Properties  】    call 
 
    // Stereotype attributes, as if they were attributes inside a class, are used [ this. Stereotype properties can also be used as public static properties .prototype. Stereotype attribute 
    Atest.prototype.sex = " male ";
 
    Atest.Run(); // Class methods are also static and can be used directly    【  object . A static method () 】 
    Atest.prototype.msg();// When a prototype method is used as a static method .prototype. methods () 】  
    alert(Atest.prototype.sex);// Object when the stereotype property is used as a static property .prototype. methods () 】 
    var a = new Atest("zhangsan");// Object methods and prototype methods need to be instantiated before they can be used 
    a.hello();// Object methods must instantiate the object 
    a.msg();// The prototype method must instantiate the object 
    alert(a.age):// Error, public static property can only be used    【  object . Property] call 
 
    //ps: Try to define methods as prototype methods, which save space by avoiding the construction of properties or methods every time the constructor is called , Create objects fast .
  </script>


Related articles: