On the prototype in JS

Source: Internet
Author: User

1. Introduction

?? Inheritance (inheritance), Encapsulation (encapsulation), and polymorphism (polymorphism) are the main features of object-oriented mechanisms. In JS, there is no "class" concept, nature can not directly do Java, C + + commonly used to extends, implements and other operations. But in a sense, JS is a purely "object-oriented" programming language, because JS is everywhere objects (functions are objects), and as a functional scripting language, is inherently polymorphic.
?? Many articles on the internet discuss how to design class and object-oriented mechanism in JS, the ideas of these articles focus on how to implement the same mechanism in JS with the object-oriented implementation mechanism in Java and C + + Strictly. But in my opinion, since JS in the definition of "class", we should fully enjoy the pure object of JS mechanism brought convenience.

2. Explore prototype

?? What is class in object-oriented? In essence is a "template", like making moon cakes, we need a moon cake mold, and the use of mooncakes made of moon cakes basically consistent.
?? So in JS, how to define the "Moon Cake Mold"? JS provides a constructor, the constructor is the "Moon Cake Mold" in JS. Consider the following code for the production of mooncakes in our factory:

var 序列号 = 0;function 我厂月饼模子(厂名,日期){    this.序列号 = 序列号++;    this.厂家名字 = 厂名;    this.生产日期 = 日期;}var 我厂月饼1 = new 我厂月饼模子("我厂","20180806");var 我厂月饼2 = new 我厂月饼模子("我厂","20180807");

?? In the above code we define the "I Plant Moon cake Mold" This constructor (if you use the English name to capitalize the first letter), through the "new" Operation made two mooncakes: Mooncake 1 and Mooncake 2, but also on the moon cakes on the name of the factory and the production date. In addition to the keyword "class" Does not appear, the code and Java, C + + code is so similar (note that JS does not support function overloading, so the constructor of the same function name cannot be overloaded by JS).
?? I plant the moon cake production line to run up. However, the market is brutal, there are many moon cakes manufacturers, they produce mooncakes each has its own characteristics. We found that a friend of a factory to provide non-baked mooncakes, can be bought home by consumers to bake their own. We bought a factory a moon cake, which is defined as:

var  A厂月饼1 = {    月饼形状: "圆形",    生产日期: "20180706",    烘烤: function () {        console.log("提供烘烤功能");    }}

?? JS in the constructor has the prototype property, when the constructor "I Plant moon Cake Mold" Prototype property set to a factory Mooncake 1, produced by the "I plant mooncake 1" can directly refer to the properties of the prototype object, as shown in the following code:

我厂月饼模子.prototype = A厂月饼1;var 我厂月饼1 = new 我厂月饼模子("我厂", "20180806");我厂月饼1.烘烤();

?? Now I plant the production of mooncakes also has a baking function, and has a shape feature "round", the production date is "20180806". "I plant mooncake 1" of the object attribute 1 is shown:

?? Figure 1 can see the prototype chain between the objects as: I plant moon Cakes 1->a Factory mooncake 1->object->null.
?? A factory production of the Moon cake shape can be changed, can be made "square", can also be made "round", after with a factory technician exchange, we got a factory production of moon cakes, the following constructor:

function A厂月饼模子(形状, 日期) {    this.月饼形状 = 形状;    this.生产日期 = 日期;    this.烘烤 = function () {        console.log("提供烘烤功能");    }}

?? It is obvious that a factory use this moon cake mold can make a variety of shape of the moon cakes, according to the previous method, we use a factory production of moon cakes as "I plant moon cake Mold" prototype, can only fix a shape, now we also hope that in the use of "I plant Moon cake Mold", you can make different shapes of mooncakes. What do we do? Method is in the "I Plant Moon cake Mold" quoted "a Factory Mooncake mold", refer to the following code:

function 我厂月饼模子(形状,厂名, 日期) {    A厂月饼模子.call(this,形状);    this.序列号 = 序列号++;    this.厂家名字 = 厂名;    this.生产日期 = 日期;}var 我厂月饼1 = new 我厂月饼模子("方形","我厂", "20180806");

?? Look again at the "I plant mooncake 1" object, found that there is a "square" this property. As shown in 2.

?? Unlike Figure 1, "I plant Moon Cakes 1" Object prototype chain has changed, because this time, we do not use "I plant moon cake Mold" of the prototype.
?? So far, it seems that everything has been settled, I plant not only retains the original mooncake features, but also contains a factory of moon cake features, everything seems to be so beautiful. But it wasn't long before we found out--it was another situation. A factory production of mooncakes provides a DIY color matching function, the user can be based on the moon cake to provide color matching package for the moon cakes, this function is popular with some specific groups of people.
?? Contact a factory technician, found that they "a factory moon Cake Mold" has been modified, in the prototype added a color matching function, the code is as follows:

A厂月饼模子.prototype.配色 = function(){    console.log("提供配色功能");}

?? If we want to continue to share "a factory moon Cake mold" of the "color" function, or to find a way from prototype, this time we in the original code "a factory moon Cake Mold" prototype set as a generic "a factory moon Cake mold" generated "a factory mooncake" (constructor call without parameters ), the complete code is as follows:

function A厂月饼模子(形状, 日期) {    this.月饼形状 = 形状;    this.生产日期 = 日期;    this.烘烤 = function () {        console.log("提供烘烤功能");    }}A厂月饼模子.prototype.配色 = function(){    console.log("提供配色功能");}var 序列号 = 0;function 我厂月饼模子(形状,厂名, 日期) {    A厂月饼模子.call(this,形状);    this.序列号 = 序列号++;    this.厂家名字 = 厂名;    this.生产日期 = 日期;}我厂月饼模子.prototype = new A厂月饼模子();var 我厂月饼1 = new 我厂月饼模子("方形","我厂", "20180806");

?? Look again at the "I plant mooncake 1" object, 3, already has the function of color matching (please note that the prototype chain has changed).

?? To now, finally can hush a breath, a factory again in prototype added new features, our code does not have to change.

3. Using prototype

?? In the example of the last mooncake die, we explored the prototype, then prototype is a kind of existence, let us summarize:
?? 1. prototype belongs to the constructor, which is represented in the object using the constructor new, using proto .
?? 2. The attributes contained in the prototype object, including function properties, are shared by objects built using constructors. In a sense, the prototype object is the parent object.
?? Let's summarize how to use prototype in different scenarios based on the examples in the previous section. For the sake of description, we will need to share other object properties of an object called a child object, the constructor used to generate the child object is called the child constructor, the object that provides the shared property is called the parent object, and the constructor used to generate the parent object is called the parent constructor.
?? We summarize the following rules:
?? 1. If a child object wants to share only the attributes defined in the parent constructor, the child constructor calls the parent constructor, and it is important to note that the parameters of the child constructor may need to be adjusted.
?? 2. If the child object wants to share all the attributes in the parent constructor and prototype: When the parent constructor has no arguments, only the prototype of the assignment child constructor is required to use the parent constructor new, a parent object, and when the parent constructor has parameters, the Not only the prototype of the assignment sub-constructor is a parent object that uses the parent constructor new (the constructor takes no arguments), but also the parent constructor (the parameter in the parent constructor) is called in the child constructor.
?? When we use DDD (domain driven design) thinking to design software, we design entities, value objects, and aggregations in the domain when modeling.
?? The largest number of domains should be entities, which are also objects in programming languages. Imagine that we use JS to program the domain model, when we use the "Object sharing attribute" view of the original "object inheritance" relationship, can also achieve the use of Java, C + + and other programming languages to achieve the performance.

4. Summary

?? Prototype is a often confusing concept in JS, which is confusing because people always want to combine it with the object-oriented classical framework, instead of tying up their own thinking. JS is a purely object-oriented system, using the prototype of constructors to realize the sharing of object attributes, this paper explores the nature of prototype and sums up the rules of prototype usage.

On the prototype in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.