js prototype object

Prototype object

  • For every function we create, the parser will add an implicit attribute prototype to the function

  • This property corresponds to an object, this object is the so-called prototype object

  • If the function is called as a normal function, the prototype has no effect

  • When a function is called in the form of a constructor, the object it creates will have an implicit attribute, which points to the prototype object of the constructor. We can access the attribute through __proto__
    Insert picture description here

  • The prototype object is equivalent to a public area, all instances of the same class can access this prototype object

  • We can uniformly set the common content in the object into the prototype object

  • When we access a property and method of an object, we will first look for it, if there is one,
    we will use it directly, if not we will look for it in the prototype object, and if we find it, we will use it directly

  • When creating a constructor, you can set the common attributes and methods of these objects to the prototype object of the constructor. In this way, you don’t need to add them separately for each object or affect the global scope. You can make each Objects have these properties and methods
    -

  • When using in to check whether an object contains a certain property, it will return true if there is no prototype in the object

Insert picture description here
mc does not have a name attribute in this object, but it also returns true if there is one in its prototype

  • You can use the hasOwnProperty() of the object to check whether the object itself contains the property. Use this method to return true only when the object itself contains the property
    Insert picture description here

  • The prototype object is also an object, so it also has a prototype.
    When we use the properties and methods of an object, we will first look for it in
    itself. If there are in itself, we will use it directly.
    If not, we will look for it in the prototype object. If there are in the prototype object, we will use it.
    If not, look for the prototype of the prototype object
    until the prototype of the Object object is found. If it is not found in the prototype of the Object, return undefined

E.g:

console.log(mc.__ proto__ .__ proto __.hasOwnProperty);

Guess you like

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