What design patterns were used to design the javascript language?

As a front-end engineer, you believe that mastery of javascript is an essential skill. How many design patterns do you know? What design patterns do you know? First of all, we need to know that Design patterns are not unique to javascript. Design patterns exist in many languages. Therefore, Design patterns are a kind of programming thought. These patterns are usually experienced programmers use of object-oriented programming and design pattern is a software developer in the face of the programming problems when a solution of these solutions will be a good programmers lots and lots of tests and improvement, is a kind of thoughts, the evolutionary process, to eventually be recognized by the vast majority of people, thus was born a design pattern.

Here’s what Wikipedia says about design patterns:

Design Pattern is a set of repeatedly used, most people know, classified, code Design experience summary. The purpose of using design patterns is to make code reusable, make it easier for others to understand, and ensure code reliability. Design patterns make code writing truly engineering; Design patterns are the cornerstone of software engineering, just like the structure of a mansion.

Classification of design patterns

In the book design Patterns, 23 design patterns are summarized, which can be divided into creative patterns, structural patterns and behavioral patterns in terms of intent.

In the case of the creative pattern, creating an object is an abstract behavior, and what objects can be created can be changed, so the purpose of the creative pattern is to encapsulate the changes of those objects. Structural patterns encapsulate combinatorial relationships between objects. Behavioral patterns encapsulate changes in objects.

Creative patterns: singleton, Abstract Factory, Builder, Factory, prototype. Structural mode: adapter mode, bridge mode, decorative mode, composite mode, appearance mode, share mode, proxy mode. Behavioral patterns: template method pattern, command pattern, iterator pattern, Observer pattern, mediator pattern, memo pattern, Interpreter pattern, state pattern, Policy pattern, responsibility chain pattern, Visitor pattern.

Prototype pattern and javascript object system based on prototype inheritance

To understand the design philosophy of javascript, it is important to understand its history. Brendan Eich used Self and Smalltalk, two prototype-based languages, as a reference when designing object-oriented systems for javascript. So the javascript language is designed with this in mind, using the prototype pattern of design patterns.

  • The prototype pattern is not only a pattern, but also known as a programming paradigm.

Use the clone prototype pattern

In terms of design patterns, prototyping is a pattern used to create objects. Unlike static languages, when we create an object, we don’t specify its type and then create the object. Prototyping takes another approach, cloning. We don’t need to focus on the type of object, we need to clone an identical object whenever we need to, and that’s the prototype pattern.

So, since the prototype pattern creates objects by cloning, if we need an object that looks exactly like an object, we can use the prototype pattern.

It is precisely these characteristics that determine whether the key to the implementation of the prototype pattern is whether the language supports clone and provides clone methods. ECMAScript 5 provides the ** object.create ()** method, which can be used to clone objects as follows:

var Person = function(){
  this.name = 'Snine'.this.age = 22.this.height = 173
} 
var person = new Person();
person.name = 'wang';
person.age = 25
person.height = 175
let clonePerson = Object.create(person)
console.log(person.name)
console.log(person.age)
console.log(person.height)
Copy the code

Cloning is a means of creating objects

We know that the prototype pattern can clone an identical object, but the real purpose of the prototype pattern is not to get such an object, but to provide such a convenient means to create a class, cloning is only the process and means of creating this class. A lot of static languages like Java are very strict about types, which makes doing something like new very rigid and inflexible, and it takes extra code to solve this problem, whereas javascript is incredibly flexible, so you don’t have to worry about the specific type of the object, It’s like a little boy pointing at a plane and saying, “I want this.” I don’t need to know what it is, but I can understand what it is. So in languages like javascript, it’s very easy to create objects, there are no coupling problems, and prototype patterns don’t make a lot of sense from a design pattern perspective. But javascript itself is an object-oriented programming language based on prototypes, and its object system is built using the prototype pattern, which is more appropriately called the prototype programming paradigm.

Delegation mechanism based on prototype chain

To create this class, we need to clone an Object. Under this class, they all have the same ability to eat, so Aniam can all eat. At this time, we will create an Object Dog. It can also emit calls, so there are three classes, which we represent in code:

var Aniam = new Object()
Aniam.eat = function(){
  this.Aniam = function(){ congsole.log('I can eat now.')}}var Dog = Object.create(Aniam)
Dog.say = function(){ console.log('NOW I can scream.')}console.log(Dog.say())
console.log(Dog.eat())
Copy the code

The code above represents such a process, so can you find a relationship? Aniam comes from Object, Dog comes from Aniam. They are layers. In a nutshell, we understand them as ABC, B comes from A, C comes from B, in turn, A gives birth to B, B gives birth to C, and C can go on and on, forming a powerful animal kingdom. Can we understand the relationship here?

Now he wants to make a sound, but he doesn’t have the ability to say(). What do we do? We go to Aniam, who gave birth to us, and Aniam can help the Dog do this. But you can do that for me, and if Aniam doesn’t have it, then move on. I’m sure you’re familiar with javascript prototype chains, but we’re talking about the idea of prototype patterns here, so do you get it? Shall we sum it up?

The basic paradigm of archetypal patterns

  • All data is an object.
  • To get an object, not by instantiating the class, but by finding an object and cloning it as a prototype.
  • The object will remember his principles
  • If the object cannot respond, it delegates the request to its prototype

Prototype inheritance in JavaScript

Now that we’ve summarized the basic paradigm of archetypal patterns, do you think JavaScript follows them? Let’s discuss how JavaScript builds its own object system based on these rules

1. All data is objects

JavaScript was designed to emulate Java by introducing two sets of mechanisms: Primitive datatypes, reference datatypes (object types), from this point of view, it’s not a very good idea. JavaScript was originally designed to say that everything except Undefined should be objects, and in order to do that, Basic data types such as Number, Boolean, and String can also be wrapped as objects using wrapper classes,

So, we can’t say that JavaScript is all objects, but we can say that most of it is objects, so believe that in JavaScript there is also a root object in the prototype, just like the fission, clone parent has a source, and in fact, The root Object in JavaScript is an empty Object called Object.prototype, from which all JavaScript we see everywhere comes.

2. To get an object, not by instantiating the class, but by finding an object and cloning it

We don’t see the clone action obvious in JavaScript, is it not followed? Var obj = new Object() or var obj2 = {}. At this point, An Object. Prototype is cloned from the engine, and we don’t need to worry about it.

function Person( name ) {
  this.name = name
};
Person.prototype.getName = function () {
  return this.name
}
var people = new Person('Snine')
console.log(people.name); 
console.log(people.getName())
Copy the code

First of all, we need to clarify that JavaScript has no concept of classes. Unlike Java, which is a object-oriented language, it has no concept of classes or interfaces, that is, it cannot define abstract classes or implement inheritance. However, for programming purposes, we modeled the behavior of the class and inheritance, namely the constructor, which is a function that has a set of properties and behaviors as a function body and can pass in values as function arguments. It is the equivalent of a class constructor in Java, and can be used to simulate object creation through New if needed.

3: The object remembers its prototype

So, in this case, Person is not a class, it’s a constructor, and first of all in JavaScript, functions can be used directly, they can be used by New, and when New is used, it’s a constructor, and when you call a function using the New operator, Clone the objec.prototype object and perform some additional operations. In Browsers like Chrome and Firefox, the *proto * property of an object is exposed, and we can use this property to find the prototype of an object. We know that if an object cannot perform a certain method, it will delegate its prototype to perform the execution. So how does it upload its request to its prototype? This is the ___proto _ attribute, through which the parent can be found.

4: If an object cannot respond to a request, it delegates the request to its prototype

This rule is the essence of prototype chain inheritance. Unlike other object-oriented languages, JavaScript is not cloned from other objects. In fact, every Object is cloned from Object. So, although all objects are cloned from the root Object, our prototype is not limited to object. prototype. We can dynamically point to other objects, and when Object A needs to borrow the power of Object B, You can optionally point your own prototype to B to achieve the inheritance effect, for example:

var A = function(){}
A.prototype = {name:'Snine'}

var B = function(){}
B.prototype = new A();

var b = new B();
console.log(b.name)   / / output Snine
Copy the code

We define A type A, A, b to A prototype of A name attribute, and then the prototype to A, b to new A b, then b to enter name went back for it when its prototype b, b prototype point to an A, so we go to find A name attribute output, this is A complete prototype chain, is also A borrowed from relationship.

conclusion

  • JavaScript is a language designed with a prototype pattern
  • Any Object in JavaScript is cloned from Object.prototype
  • The relationship between JavaScript’s prototype chains points to the pointer property as the hidden property _ _proto _ _.
  • JavaScript’s prototype chain is not infinite; it only reaches the root start point of the Object. Prototype

extension

Peter Novig once said that design patterns complement the language, and if you want to use design patterns, you should find a better language.

Design patterns often reflect the shortcomings of the language, but as web front-end developers, we believe that JavaScript is still the only choice for a long time. Although we can’t just switch languages, the language itself is evolving. Perhaps one day a pattern will be found to exist naturally in language, just as Object.create is a natural form of archetypal patterns. Using object.create better captures the essence of the archetypal pattern, but creating objects using this method is not very efficient and is generally slower than objects created by constructors. Also, ** object.create (null)** creates an Object without a prototype.

The class ES6

ECMAScript 6 has a new Class syntax that makes JavaScript look more like a class-based language, but behind it is the creation of objects through prototypes. Classes are created in the same way as before. This article uses ES5 writing method to parse JavaScript design ideas for home, hope you can understand this language design more