This is the first day of my participation in Gwen Challenge

What are design patterns

Before we look at prototyping patterns, let’s look at what a design pattern is. A design pattern can be understood as:

  1. fromobject-orientedThe Angle of departure through onencapsulation.inheritance.polymorphism.combinationAnd so on the repeated use of technology, refining somereusableObject-oriented design techniques.[1]
  2. Design patterns are designed in part to compensate for the shortcomings of object-oriented programming. [1]

But JavaScript does not have the inheritance of traditional object-oriented languages, nor does it have the support of abstract classes and interfaces. With this article as the beginning of JavsScript design patterns, let’s talk about design patterns in JavaScript.

What is a prototype pattern

I believe we all know that JavaScript is an object-oriented language based on prototype, and its object system is built using prototype pattern. So what is a prototype pattern? The prototype pattern is a pattern used to create objects. We do not need to know the specific type of the object, but directly find an object and clone it to create an identical object [1]. In Javascript, cloning can be implemented using the object.create method.

For example, let’s say we mass-produce war robots 🤖 in a game’s Arsenal, each with a default health of 100 and rank 1. Now our spies have stolen some core technology from enemy factories and applied it to our robots. Each default parameter is changed to 200 health and level 2.

So in JS you can write it like this

    var Machine = function(){
        this.blood = 100;
        this.level = 1;
    }
    
    var machine = new Machine();
    machine.blood = 200;
    machine.level = 2;
    
    var cloneMachine = Object.create(machine);
    
    console.log(cloneMachine);
Copy the code

The output



So, every time we callObject.create(machine)It is equivalent to producing a war robot, and the robots produced are upgraded robots 🤖️

We can also see that by callingObject.createMethod to quickly create a new object,He creates objects by cloning.

Prototype programming paradigm

JavaScript, of course, is a weakly typed language, it is very easy to create objects, there is no type coupling problem, and its object system is based on prototype patterns. As mentioned earlier, design patterns are designed in part to compensate for the shortcomings of object-oriented programming, so prototype patterns don’t seem to make much sense in JavaScript, where the object system is built on them. The prototype pattern is better known in JavaScript as the prototype programming paradigm.

The basic rules of the prototype programming paradigm

  1. All data is an object
  2. You get an object not by instantiating the class, but by finding an object as a prototype and cloning it.
  3. The object remembers its prototype.
  4. If an object cannot respond to a request, it delegates the request to its own prototype.

JavaScript is programmed based on prototypes, so it follows these basic rules. Here’s how JavaScript follows these rules

  • JavaScript introduces two sets of mechanisms: primitive types and object types. Because primitive types exist, most data in JS is only objects.

Of course, some primitive types can also be converted to object types, for example:

    new String('test');
    new Number(Awesome!);
    new Boolean(true);
Copy the code
  • You get an object not by instantiating the class, but by finding an object as a prototype and cloning it

    Let’s look at a piece of code

    function CreateObject(){
        var obj = new Object(),                     // Clone a new Object from Object.prototype
            Constructor = [].shift.call(arguments); // Take the first argument passed in
        obj.__proto__ = Constructor.prototype;      // Point the new object prototype to the constructor prototype passed in externally
        
        var result = Constructor.apply(obj,arguments); // Set properties for the new object
        
        return typeof result === 'object' ? result : obj; // Make sure you return an object
    }
    
    function Person(name){
        this.name = name;
    }
    
    Person.prototype.getName = function(){
        return this.name;
    }
    
    var x = CreateObject(Person,'shirley');
    
    console.log(x.name); // shirley
    console.log(x.getName()); // shirley
    console.log(Object.getPrototypeOf(x) === Person.prototype); // true
Copy the code

Var x = CreateObject(Person,’ Shirley ‘) var x = new Person(‘ Shirley ‘) Person is not a class here; there is no such thing as a class in JavaScript. It is a function constructor that can be called either as a normal function or as a constructor. When called with the new operator, the function is a constructor.

Var result = constructive.apply (arguments) var result = constructive.apply (obj,arguments) You can see from this that you don’t get an object by instantiating the class, but by finding an object as a prototype and cloning it

  • The object remembers its prototype as you can see from the code above: When we call CreateObject, Person acts as the object’s prototype and returns a new object whose __proto__ refers to the constructor’s prototype.

  • If an object cannot respond to a request, it delegates the request to its own prototype. As you can see from the JavaScript prototype chain, the instance object has a __proto__ method that points to the constructor’s prototype. When you need a property in the instance object that doesn’t have that property, look in the prototype chain until the property is found in the prototype chain. Or stop at the top of the prototype chain.

        function Animal () {}
        Animal.prototype.dog = 'wang wang';
        Animal.peototype.cat = 'meow meow';
        
        var a = new Animal();
        console.log(a.dog); / / wang wang
        console.log(a.lion); // undefined
    Copy the code

    Example A does not have the dog property, but because the third object remembers its prototype, __proto__ remembers its constructor Animal’s prototype, so when the dog property is not present in instance A, it can look up the dog property to the top of the prototype. Using this approach, you can implement a simple inheritance in JavaScript: prototype inheritance

        var obj = { name: 'test' };
        
        var ext = function() {};
        ext.prototype = obj;
        
        var a = new ext();
        console.log(a.name); // test
    Copy the code

Write in the last

  1. This article provides a brief introduction to what design patterns are, what they can be used for,
  2. Introduced what archetypal patterns are and archetypal patterns in JavaScript
  3. The rules of the prototype programming paradigm are introduced
    • All data is an object
    • If an object cannot respond to a request, it delegates the request to its own prototype.
    • The object remembers its prototype
    • If an object cannot respond to a request, it delegates the request to its own prototype.

If you find this article helpful, you can encourage the author by clicking a “like”, and if you want to learn more about JavaScript or Node, you can click here. Please point out any inaccuracies or errors in the comments section.


reference

  1. JavaScript Design Patterns and Development Practices
  2. JavaScript goes from prototype to prototype chain
  3. MDN