js constructor

Constructor

  • The constructor is an ordinary function, the creation method is no different from the ordinary function, the difference is that the constructor is used to capitalize the first letter
  • The difference between the constructor and the ordinary function is the different calling method. The
    ordinary function is called directly, and the constructor is to use the new keyword.
  • The execution process of the constructor
    1. Create a new object immediately
    2. Set the newly created object as the this of the function. In the constructor, you can use this to refer to the newly created object.
    3. Execute the code of the function line by line.
    4. Set the newly created object . Object is returned as return value
    Insert picture description here
  • Objects created using the same constructor are called a class of objects, and the constructor is also called a class
  • The object created by the constructor is called an instance of the class
  • Use instanceof to check whether an object is an instance of a class.
    Syntax: the
    object instanceof constructor
    returns true if it is, and false if it is not

console.log(per instanceof Person); //Used to check whether the object is an instance of a class

  • All objects are descendants of Object,
    so any object will return true when an instanceof check is performed.

  • When called in the form of a calling function, this is window

  • When it is called in the form of a calling method, whoever called this is who

  • When called in the form of a constructor, this is the newly created object.
    Insert picture description here
    Create a Person constructor.
    In the Person constructor, add a sayName() method to each object.
    Currently our methods are created inside the constructor.
    That is to say, a new sayName() method will be created every time the function is executed.
    All instances sayName are unique.
    This causes a new method to be created every time the function is executed, and the methods are exactly the same.
    This is completely unnecessary. , It is possible to make all objects share the same method

Insert picture description here
Define the method in the global scope, so that no matter how many times the function is executed, the method will only be created once

Guess you like

Origin blog.csdn.net/weixin_48769418/article/details/108279000