1024programmer Java [Mechanism] JavaScript prototype, prototype chain, inheritance

[Mechanism] JavaScript prototype, prototype chain, inheritance

1. The concept of prototype and prototype chain

When js creates an object, such as calling it obj, They will secretly add a reference to him. This reference points to an object, such as yuanxing.

This object can provide attribute sharing for the object that refers to it. , for example: yuanxing has an attribute name, which can be accessed by obj.name.

This can provide an object for attribute sharing. , is called the prototype of the previous object

And the prototype itself is also an object, so it will also have its own prototype. This continues layer by layer until it finally points to null, which forms Prototype chain

How is the prototype mechanism of js implemented?

2. Prototype implementation

Let’s look at an example first:

// code-01
let obj = new Object({name:'xiaomin'})
console.log(obj.name)
console.log(obj.toString())
// xiaomin
// [object Object]

We first create an object obj, which has an attribute name

The attribute name was created by us, but when creating obj, the toString attribute was not created for it. Why can obj.toString() be accessed?

prototype attribute

Let’s first take a look at the Object.prototype attribute

We found that there is toString here attributes, so in fact Object.prototype is the prototype of obj. According to the concept of prototype, it can provide attribute sharing for obj

So when obj.toString() is used, first search in the attributes of obj. If not found, just search in the prototype of objObject.prototype can be found, so the call is successful

proto property

So how did obj find the prototype? Let’s print the obj attribute and take a look:

We found that obj, in addition to the name we created, also has a __proto__ attribute, Its value is an object, so what is it equal to?

We Found that obj.__proto__ points to Object.prototype

At this point, we can briefly summarize the basic mechanism of prototype implementation in js language p>

  • When creating an object obj, a __proto__ attribute will be added to it
  • __proto__ attribute points to the prototype object of obj‘s constructor
  • When accessing an attribute of obj, it will first search on its own attribute. If not found, it will search on its prototype (actually __proto__ Look for the properties of the object pointed to)

Constructor

This has a constructor concept, in fact, constructor is an ordinary function. When this function is used to new a new object, it is called the new object’s Constructor

In the above example, Objec is the constructor of obj,

Here we need to distinguish between Object and object. The former is a function built into js, ​​and the latter is the basic data type of js (number, string, function, object, undefined)

3.What does new actually do

The new keyword is mentioned above, so in what it actually does What did you do?

The above code code-01 uses the system’s built-in function Object to create an object, so now we use the function we created to create a new object Take a look:

//code-02
function human(name){
this.name = name
}
human.prototype.say = function( ){
alert('my name'+this.name)
}
let xiaomin = new human('xiaoming')
console.log(xiaomin.name)
xiaomin.say ()

The human here is the constructor of the new object xiaoming

We put the new Print the created object xiaoming to see:

We see that xiaoming has an attribute name, and xiaoming.__proto__ is completely Equal to the human.prototype of the constructor, this is its prototype

From here we can summarize the basics of new Function:

  • Point this of the constructor to the newly created keyword to implement classes and inheritance. In fact, this is the syntax of ES6. It is actually a kind of syntactic sugar. The essential principle is the same. Let’s take a look at the basic usage first:

    Usage

    //code-05
    class human {
    //1 .There must be a constructor
    constructor(name) {
    this.name = name;
    }//2. There cannot be commas `,`
    sayName() {
    console.log ("sayName:", this.name);
    }
    }
    class user extends human {
    constructor(params) {
    //3. Subclasses must use `super`, Call the constructor of the parent class
    super(params.name);
    this.age = params.age;
    }
    sayAge() {
    console.log("sayAge:", this.age);
    }
    }
    let person = new human("human");
    let xiaoming = new user({ name: "xiaoming", age: 27 });
    console.log("---- person-----");
    console.log(person);
    person.sayName();
    console.log(" ---- xiaoming-----");
    console.log(xiaoming);
    xiaoming.sayName();
    xiaoming.sayAge();

    Execution result:

    We see that the execution result is the same as the above code code-04, but the code is obviously much clearer. A few things to note:

    • The class class must have a constructor constructor,
    • class Functions in a class cannot be separated by ,
    • If you want to inherit the parent class, in the constructor of the subclass, you must first execute superThe constructor of the parent class to be called

    Same

    It is said above that the way of writing class is actually the same as above in principle Same, let’s verify it

    1. First look at what types user and human are

      See here came out, so although it is modified by class, it is still a function in essence, which is the same as the user and human functions in the code code-04

    2. Let’s take a look at the prototype attribute

      It can be seen here that sayName, sayAge are all defined in human.prototype and user.prototype, the same as in code code-04

    3. Let’s take a look at the prototype chain again

      This is the same as the prototype chain in the code code-04: xiaoming->user.prototype->human.prototype

    Difference

    After looking at the similarities, now let’s look at the differences:

    1. First of all, the difference in writing
    2. The function declared by class, Must be called with new
    3. Member functions inside a class do not have a prototype attribute and cannot be called with new
    4. The code within the class is automatically in strict mode
    5. There is no variable promotion in class declaration, which is the same as let, for example:

      //code-06
      console.log(name_var);
      var name_var = " xiaoming";
      //undefined, no error will be reported, var declaration has variable promotion
      console.log(name_let);
      let name_let = "xiaoming";
      // Uncaught ReferenceError: Cannot access ' name_let' before initialization
      //Error, let statement does not have variable promotion
      new user();
      class user {}
      // Uncaught ReferenceError: Cannot access 'user' before initialization
      //Error report, class declaration does not have variable promotion

    6. Methods in class are not enumerable, such as:

      //code-07
      class human_class {
      constructor(name) {
      this.name = name;
      }
      sayName() {
      console.log(" sayName:", this.name);
      }
      }
      function human_fun(name) {
      this.name = name;
      }
      human_fun.prototype.sayName = function ( ) {
      console.log("sayName:", this.name);
      };
      console.log("----------human_class------- ----");
      console.log("prototype attribute", human_class.prototype);
      console.log("prototype enumeration", Object.keys(human_class.prototype));
      console.log("----------human_fun-----------");
      console.log("prototype attribute", human_fun.prototype);
      console.log("prototype enumeration", Object.keys(human_fun.prototype));

      Running results:

    6. Summary

    A brief summary:

    • When each object is created, it will be assigned a __proto__ attribute, which points to the prototype of the constructor that created this object, and prototype itself is also an object, so it also has its own __proto__, so A prototype chain is formed, and the final point is Object.prototype.__proto__ == null
    • It can be passed new,Object. create(), Object.setPrototypeOf(), direct assignment __proto__ and other methods to specify the prototype of an object
    • new operator actually does is: create an object, use this object as the this environment of the constructor, and point the prototype of this object (proto) to the prototype of the constructor , and finally return this object
    • Inheritance The main functions implemented are: binding pointed to by this, construction of the prototype chain
    • ES6 The syntax of class and extends can provide clearer and more concise writing, but the essential principles are roughly the same

    __ == null

  • Can be passed new,Object.create(),Object.setPrototypeOf() ,Direct assignment __proto__ and other methods to specify a prototype for an object
  • newThe actual work done by the operator is: create An object, use this object as the this environment of the constructor, point the prototype of this object (proto) to the prototype of the constructor, and finally return this object
  • inheritance are: binding pointed to by this, construction of prototype chain
  • ES6 syntax class, extends can provide a clearer and more concise way of writing, but the essential principles are roughly the same
This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/mechanism-javascript-prototype-prototype-chain-inheritance-3/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索