preface

Many development of JavaScript to achieve object-oriented programming exists a little knowledge, and many in the project practice to write are oriented to the process of programming code, therefore, I hope to start from zero to introduce some concepts of object-oriented to achieve simple object-oriented examples to let everyone including myself to deepen the knowledge of object-oriented. I hope it will be helpful to you

Object based

concept

An object is a collection of related data and methods. It is composed of variables and functions. It is usually called properties and methods.

Create method

1. Initialize the object

var person={}Copy the code

2. Add attributes (variables) and methods (functions)

var person={
                name:'aaron',
                say:function(){
                    alert('hello')
                }
            }Copy the code

3. Obtain properties and execution methods

person.name
person.say()Copy the code

Note: There are two ways to get properties and execute methods, one of which I have listed above: dot notation and the other is parenthesis notation. As follows:

person['name']
person['say']()Copy the code

For this reason, objects are sometimes called associative arrays, meaning that objects map strings to values, while arrays map numbers to values.

4. Run the screenshot

5. Set object members



Note: It is important to note that the parenthesis notation allows you to set object members by defining variable names in a way that dot notation does not.

6. The meaning of “this”

The orientation of this has always been a big headache for developers, especially when writing JS on the back end. This refers to the object at which the code is currently running. Such as:



Since the object literal executes the current object, this refers to Person. The object that this points to, like the constructor created, is the constructor instance object

advantages

At a glance, the benefits of creating objects by object literals can effectively unify the attributes and methods associated with objects, reduce the pollution of global variables, and achieve a certain degree of security (reduce the risk of defining all-variable overwriting object attributes).

Object orientation – constructors

Understand OOP ideas

For example, starting from an example in the real world, we can obtain a lot of information about a person (their address, height, shoe size, etc.), and then we will introduce them based on this information and ask them to respond. In object-oriented languages, we can describe an object through the concept of a class, which is the template that defines the characteristics of the object. With the created class, we can build on it to create objects that have properties and methods in the class, called instance objects. The objects of these instances are usually concrete people, such as teachers and students. In OOP, we can also create new classes based on this class, and these new subclasses (such as parents) can inherit the attributes (data) and methods (functions) of their parent class to use functions common to the parent object.

Therefore, by referring to a general person to a specific student/teacher relationship, we can summarize the three basic characteristics of object orientation: encapsulation, inheritance, polymorphism.

Introduction of the concept

By understanding the basic concepts of object-oriented programming (OOP), what objects are and their properties, methods, and the basic features of implementing OOP. We also learned about the common method of creating objects, object literals. We have already understood the basic concepts of objects. However, the creation of a single entity class from object literals does not achieve the encapsulation of universal objects (reality models), that is, true implementation object-oriented. JavaScript defines objects and features by building functions, and instance objects are built to inherit features through a chain of stereotypes.

Learn to build functions and object instances from examples

1. The Person() constructor creates the instance object and accesses properties and methods:



2. Other gestures for creating object instances

1.Object() constructor

var person1=new Object();
                person1.name='ace';
                person1.age=30;
                person1.greeting=function(){
                    alert('Hi! I\'m ' + this.name + '.'')
                }Copy the code

2. Use create() : This creates an object based on Person1 that has the same properties and methods as person1.

var person2=Object.create(person1);Copy the code

Object orientation — Object prototypes

Introduction of the concept

The inheritance mechanism of JavaScript is different from that of other classical object-oriented programming languages. It inherits features from other objects through prototypes.

For this reason, JavaScript is often described as a prototype-based language — each object has a prototypeobject, which is modelled on its prototype, inherits methods and properties from that prototype, which may also have a prototype, from which it inherits methods and properties, and so on. And this relationship is called the prototype chain. What we need to know is that these properties and methods are the Prototype properties defined on the instance constructor, and, of course, the instance object also has the __proto__ property, which is derived from the prototype property of the instance object, the.__proto=== constructor. Prototype.

Understanding prototype objects



From the screenshot, we can see that the Person1 instance has other attributes and methods in addition to the attribute methods in the Person() constructor, which are members of the Person() constructor prototype Object.



  
By calling valueOf, we also learned how to call a method:

1. The browser first checks if the person1 object has a valueOf() method available.

2. If not, the browser checks whether the prototype object of the Person1 object (that is, Person) has a valueof() method available.

3. If not, the browser checks to see if the Person() constructor’s prototype Object (that is, Object) has a valueOf() method available. Object has this method, and the method is called.

The prototype property

By calling the valueOf method, we can see that the properties and methods that can be inherited (there are property methods that can’t be inherited on an object, for example is()/keys()) are defined on the Prototype property. Therefore, property methods that need to be inherited by subclasses need to be defined on Prototype.

The constructor property

Each instance object has a constructor attribute, which points to the constructor that created the instance.

We can also create a new instance by adding the () form after constructor.

Modify the prototype



As you can see from the screenshot, even though the instance object person1 has been created, person1 can still be called when a method is added to the constructor Person() Prototype, indicating that the function call will call the method from the upstream object up the prototype chain.



  
As shown here, if the prototype attribute is defined, the current execution environment of this is global and undefined is returned. Also, in terms of object inheritance, it is common practice to define properties in constructors and methods in prototype properties.

Small demo- Examples to understand inheritance in JavaScript

1. Create the constructor Person and define methods on the constructor

function Person(first, last, age, gender, interests) {
      this.name = {
        first,
        last
      };
      this.age = age;
      this.gender = gender;
      this.interests = interests;
    };
    Person.prototype.bio = function() {
       alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
    };
    Person.prototype.greeting = function() {
      alert('Hi! I\'m ' + this.name.first + '.');
    };Copy the code

Create Teacher class Teacher constructor and inherit all members of the Teacher class. Create Teacher class Teacher constructor and inherit all members of the Teacher class.

 function Teacher(first, last, age, gender, interests, subject) {
      Person.call(this, first, last, age, gender, interests);
      this.subject = subject;
    }Copy the code

3. Set Teacher() ‘s prototype and constructor references



As shown, the new Teacher() constructor is created with only an empty stereotype property, so it inherits the method from the prototype of Person() :

Teacher.prototype = Object.create(Person.prototype);Copy the code



Because of the way we created Teacher’s prototype, the Teacher() constructor’s prototype property executes Person(), so we need to set the pointer to Teacher:

Teacher.prototype.constructor = Teacher;Copy the code

This way, we can implement that all methods that need to be inherited are defined in the constructor’s Prototype property so that we don’t mess with the class inheritance structure.

4. Add new greeting methods to Teacher()

Teacher.prototype.greeting = function() { var prefix; if(this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') { prefix = 'Mr.'; } else if(this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') { prefix =  'Mrs.'; } else { prefix = 'Mx.'; } alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.'); };Copy the code

5. Finally run create teacher instance, we get properties and methods inherited from the Person() constructor, with property methods only available from the teacher () constructor.

6. Object members

Through learning, we can know that the general object has three types of object members:

1. Those defined in constructor functions that are used to give object instances. Generally, it is an object attribute.

2. Those defined directly on constructors and available only on constructors. These are usually only available in built-in browser objects and are identified by being linked directly to constructors rather than instances. Such as the Object. The keys ().

3. Those defined on constructor prototypes that are inherited by all instances and object classes. Usually object methods.

Go deep — Design pattern principles

Of course, basic object-oriented programming can be achieved through the above approach, but to achieve more advanced library encapsulation and framework implementation, a good understanding of design patterns is required.

Here, I would like to list the principles of design patterns, and hope that you, including myself, have some direction to learn. The general design principles are:

1. Principle of single responsibility

2. Richter’s substitution principle

3. Dependency inversion principle

4. Interface isolation principle

5. Demeter principle

6. Open and close principle

Of course, there are also object-oriented design patterns (23), which need to be deeply understood. In fact, this is already deep in our own code, but we do not know it deeply. This is the follow-up to understand ~~~

Actual Combat: Building object — Bouncing ball (ES6 implementation)

background

Through the basic concept of object-oriented, object-oriented programming ideas and constructors, prototype implementation method to achieve a simple bouncing ball small game.

introduce

Mainly through ES6, class syntax sugar, draw the background through canvas and control the top, bottom, left and right of EVIL, eat the ball.

In the code

1.index.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Bouncing balls</title> <link rel="stylesheet" href="style.css"> </head> <body> <canvas></canvas> <script src="mainUpgrade.js"></script> </body> </html>Copy the code

2.mainUpgrade.js

const canvas=document.querySelector('canvas'); const ctx=canvas.getContext('2d'); const width=canvas.width=window.innerWidth; const height=canvas.height=window.innerHeight; //create a random number between min and max. random=(min,max)=>{ let num=Math.floor(Math.random()*(max-min+1))+min; return num; }; //create constructor for ball class Shape{ constructor(x,y,velX,velY,exists){ this.x=x; this.y=y; / / coordinates enclosing velX = velX; this.velY=velY; // Horizontal and vertical velocity this.exists=exists; / / if there is a}} class Ball extends Shape {constructor (x, y, velX velY, exists, color, size) {super (x, y, velX velY, exists). this.color=color; this.size=size; } // draw ball draw (){ ctx.beginPath(); ctx.fillStyle=this.color; CTX. Arc (enclosing x, enclosing y, enclosing the size, 0, 2 * Math. PI); // arc() draws the arc ctx.fill(); } //update ball location update (){ if((this.x + this.size)>=width){ this.velX=-(this.velX) } if((this.x - this.size)<= 0){ this.velX=-(this.velX) } if((this.y + this.size)>= height){ this.velY=-(this.velY) } if((this.y - this.size)<= 0){ this.velY=-(this.velY) } this.x+=this.velX; this.y+=this.velY; } //spy collision collisionDetect (){ for(let j=0; j<balls.length; j++){ if(! (this===balls[j])){ const dx=this.x - balls[j].x; const dy=this.y - balls[j].y; const distance=Math.sqrt(dx*dx + dy*dy); if(distance<this.size + balls[j].size){ Balls [j]. J color = this. Color = 'RGB (' + random (0255) +', '+ random (0255) +', '+ random (0255) +') '. } } } } } //create evil circle class EvilCircle extends Shape{ constructor(x,y,exists){ super(x,y,exists); this.color='white'; this.size=10; this.velX=20; this.velY=20; } draw(){ ctx.beginPath(); ctx.strokeStyle=this.color; ctx.lineWidth=3; CTX. Arc (enclosing x, enclosing y, enclosing the size, 0, 2 * Math. PI); ctx.stroke(); } //check evil location checkBounds(){ if((this.x + this.size)>width){ this.x-=this.size } if((this.y + this.size)>height){ this.y-=this.size } if((this.x - this.size)<0){ this.x+=this.size; } if((this.y - this.size)<0){ this.y+=this.size; } } setControls(){ window.onkeydown=(e)=>{ if(e.keyCode===38){ this.y-=this.velY } else if(e.keyCode===40){ this.y+=this.velY; } else if(e.keyCode===37){ this.x-=this.velX } else if(e.keyCode===39){ this.x+=this.velX } } } collisionDetect(){ for(let i=0; i<balls.length; i++){ if(balls[i].exists){ const dx=this.x-balls[i].x; const dy=this.y-balls[i].y; const distance=Math.sqrt(dx*dx+dy*dy); if(distance<this.size+balls[i].size){ balls[i].exists=false; } } } } } let balls=[]; const evil=new EvilCircle( random(0,width), random(0,height), true ); Loop () = = > {CTX. FillStyle = 'rgba (0,0,0,0.25); CTX. FillRect (0, 0, width, height); While (balls.length < 25){const ball=new ball (random(0,width), random(0,height), random(-7,7), random(-7,7), true, 'RGB (' + random (0255) +', '+ random (0255) +', '+ random (0255) +') ', the random (10, 20)); balls.push(ball); } for(let i=0; i<balls.length; i++){ if(balls[i].exists){ balls[i].draw(); balls[i].update(); balls[i].collisionDetect(); } } evil.draw(); evil.checkBounds(); evil.setControls(); evil.collisionDetect(); Window. RequestAnimationFrame (loop)/browser/implement animation and request before the next redraw call the specified function to update the animation} loop ();

Copy the code

Run a screenshot

conclusion

Through this blog post, I hope to give you a basic understanding and concept of JavaScript implementation object-oriented. If there is any improper description of the place please point out, thank you.

Author: PC. Aaron

Reference: www.cnblogs.com/aaron-pan/

The copyright of this article belongs to the author, welcome to reprint, but without the consent of the author must retain this statement, and give the original text link in the obvious position of the article page, otherwise reserve the right to pursue legal responsibility.