Home > Web Front-end > JS Tutorial > body text

Detailed explanation of JavaScript prototypes

黄舟
Release: 2017-02-22 13:22:57
Original
1025 people have browsed it


1, Foreword

The following is the ranking of various programming languages ​​since the creation of Github in 2008

Detailed explanation of JavaScript prototypes

Among them, JavaScript has occupied the first place since 2015 and has become the most used language on github. In the early days, the use of JS was mainly concentrated in browsers, but as node.js entered server development and React Native gradually moved to mobile End-to-end penetration, a full-stack era of JS is coming. And there is a famous saying in the JS world: "All applications that can be developed with JS will eventually be developed with JS." I just asked you if you are afraid?

Okay, having said all that, I don’t want to say that JS is the best language in the world (obviously PHP is, right? ←_←), nor do I think JS will replace anyone. I I just feel that JavaScript will be a language tool that everyone (not just the web side) should understand and learn.

2, Object-oriented (OOP)

2.1 Implementation ideas

Object-oriented is a programming idea that everyone is familiar with. It is an abstraction of the real world. At present, The main basis for OOP language to implement object-oriented is classes, which map the real world through class encapsulation and inheritance. Including Java, C#, and even python, they all implement object-oriented design through class design. But when you think about it carefully, you will feel that there is a problem, because there is no concept of class in the real world, only different objects. In the real world, the inheritance relationship occurs between objects and objects, not classes. For example, children are objects, parents are also objects, and children (objects) inherit from parents (objects)

JS is also an object-oriented programming language, but its idea of ​​​​implementing objects is based on prototype (prototype) , instead of a class. This idea is also called Object Link Other Object, that is, the real-world relationship (such as inheritance) is directly mapped on the object.

2.2 Prototype concept

In fact, I have studied related concepts for several days. In addition to the prototype concept itself, the generation of objects associated with it, constructors, the difference between proto and prototype, and why objects There is no prototype attribute pointing to the prototype, but use proto to point to the prototype?

Okay, let’s talk about the concept of prototype first. Everything in JS is an object, and each object has a prototype (except Object). This prototype is probably like the parent class in Java, so basically you can think of the prototype as the parent object of this object, that is, every object (Except Object) internally stores its own parent object, and this parent object is the prototype. If a generally created object does not specify a prototype, its prototype is Object (this is very similar to all classes in Java inheriting from the Object class by default).

2.3 Object creation

In JS, there are many ways to create objects, the most common ones are as follows:

//第一种,手动创建
var a={'name':'lala'};   

//第二种,构造函数
function A(){
    this.name='lala';
}
var a=new A();

//第三种,class (ES6标准写法)

class A{
    constructor(){
        super();
        this.name='lala';
    }
}
var a=new A()
//其实后面两种方法本质上是一种写法
Copy after login

The prototype (parent) of the object created by these three writing methods Object) are all Objects. It should be mentioned that ES6 uses keywords such as class and extends to wrap the constructor into a class concept in the form of syntactic sugar, making it easier for everyone to understand. It is hoped that developers will no longer spend energy paying attention to prototypes and prototype chains, and it also fully demonstrates that the design intention of prototypes is the same as that of classes.

2.4 View object prototype

After objects are created, there is more than one way to view their prototype. In the past, the proto attribute of the object was generally used. After the launch of ES6, it is recommended to use Object.getPrototypeOf( ) method to get the prototype of the object

function A(){
    this.name='lala';
}
var a=new A();
console.log(a.__proto__)  
//输出:Object {}

//推荐使用这种方式获取对象的原型
console.log(Object.getPrototypeOf(a))  
//输出:Object {}
Copy after login

No matter how the object is created, the default prototype is Object. The special point that needs to be mentioned here is that the object is created through the constructor, and the function A itself is also An object, and A has two attributes pointing to the prototype, namely proto and prototype, and the two attributes are not the same.

function A(){
    this.name='lala';
}
var a=new A();
console.log(A.prototype)  
//输出:Object {}

console.log(A.__proto__)  
//输出:function () {}
console.log(Object.getPrototypeOf(A))
//输出:function () {}
Copy after login

The prototype attribute of the function can only be used when it is created as a constructor. The value of its own prototype attribute is assigned to the object's prototype. In fact, as the function itself, its prototype should be the function object, and then the prototype of the function object is Object.

In short, it is recommended to use the methods recommended by ES6 for viewing prototypes and setting prototypes.

2.5 Usage of prototype

In fact, the usage of prototype and class inheritance are the same: when you want to use the properties of an object, point the prototype of the current object to the object, and you You have the right to use the object.

function A(){
    this.name='world ';
}
function B(){
    this.bb="hello"
    }
var a=new A();
var b=new B();

Object.setPrototypeOf(a,b);
//将b设置为a的原型,此处有一个问题,即a的constructor也指向了B构造函数,可能需要纠正
a.constructor=A;
console.log(a.bb)
//输出 hello
Copy after login

(Supplement)

If you use ES6 to do it, it will be much simpler, and it does not even involve the prototype attribute

class B{
     constructor(){

        this.bb='hello'
     }
}
class A  extends B{
     constructor(){
        super()
        this.name='world'
     }
}

var a=new A();
console.log(a.bb+" "+a.name);
//输出hello world


console.log(typeof(A))
//输出  "function"
Copy after login

How about? Is there no trace of the prototype at all? It is just class inheritance, but you can also see that the type of class A is actually function, so in essence, class is a kind of syntactic sugar in JS, and the essence of JS inheritance is still prototype. However, ES6 introduces class and extends To cover up the concept of prototypes is also a very friendly move for programmers who have long studied object-oriented programming languages ​​​​based on class inheritance.

My suggestion is to understand the prototype as much as possible and use syntax sugar like class as much as possible.


2.6 Prototype chain

This concept has actually become relatively simple. It can be compared to the inheritance chain of a class, that is, the prototype of each object is traced upward until it reaches Object, which forms a The chain connects the objects in it. When searching for the properties of the current object, if it is not found, it will be searched along this chain until it reaches the Object. If it is not found yet, it will report undefined. This means that your prototype chain cannot be too long, otherwise efficiency problems will occur.

3, Summary

  • Understanding of the concept of prototype

    • Inheritance of analogy classes, the prototype of an object can Understand as the parent object of the object

  • Use of prototype

    • Use ES6 standards as much as possible, use class, extends , Object.getPrototype(), Object.setPrototype(), etc.

  • Points to note

    • Prototypal inheritance The chain should not be too long

    • When specifying the prototype, note that the constructor will also change.

4, Postscript (Supplement)

Some people think that my analysis is very abstract, so I will summarize it again. If you want to understand JS in one sentence What is the prototype of an object? That is, the prototype of an object refers to the parent object of the object. Every object has a parent object, and the parent object itself also has a parent object (grandfather object?). As for the prototype chain, it is very similar to the concept of family trees in the past. You can trace your father, your grandfather, your great-grandfather all the way to the end. This forms a chain. If each person in it is compared to an object, then this chain It's the prototype chain.

The above is the detailed explanation of JavaScript prototype. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template