The sea is wide by diving, the sky is high as birds fly. Hey how are you! I’m Ed Qin. 😄

There are ten thousand Hamlets in ten thousand people, ten thousand understanding of object-oriented thought in ten thousand developers. Here I only shallow elaborated me to face the understanding of object thought, do not like light spray, welcome everyone comment area leave a message or join “Qin Aide front end communication group” discussion.

The basic concept

In programs, we use objects to model the real world, simplifying and providing access to functionality that would otherwise be difficult (or impossible) to use

This explanation, taken from MDN, is a mouthful to read.

Here we can use cramming to understand object orientation, which roughly means that if it looks like a duck, it is a duck. The difference between humans and machines is that humans have subjective consciousness and machines don’t have a creature with a pointy mouth, a flat head, a quack quack and swimming, so this is the class that we use object thinking to construct a duck. A machine doesn’t have the same subjective assumption as a human does that this is actually a goose.

Object composition

A basic object is made up of several data types, which can be divided into behaviors and properties on a larger scale

Attributes: All data types can be considered attributes of the object (ducklings weight, wings, feet, etc are attributes)

Behavior: Generally refers to the function that gives the object the ability (duckling can swim, so swimming is the behavior of duckling)

Instantiate an object

At this point, we have created a duck class, and the duck is only in an initial state, equivalent to being frozen in ice. We need to unseal the duck and instantiate the duck object using the new keyword. This gives us a brand new duck object.

What exactly does the new keyword do? Refer to the following code:

var obj = {}; Var Constructor = [].shift.apply(arguments); var Constructor = [].shift.apply(arguments); // Point the new object's internal attribute __proto__ to the prototype of the Constructor, so that the new object can access the properties and methods in the prototype. Var ret = constructive. apply(obj, arguments); Return typeof ret === "object"? Return typeof ret === "object"? ret : obj;Copy the code

Object this

For this problem, many beginners are confused by the “This” point. The only thing we need to remember about this is that it refers to whoever is calling it, and this refers to the execution environment that is currently calling it

Classic example:

var obj = {
  foo: function () { console.log(this.bar) },
  bar: 1
};

var foo = obj.foo;
var bar = 2;

obj.foo() // 1
foo() // 2
Copy the code

Data types in JS are divided into basic data types and reference data types. Base data types are accessed by value, and reference data types are accessed by reference. Object puts all the references on the stack and all the values on the heap, so to get an object value, you get the reference to the object, and then you find the value based on the reference. If the reference corresponds to a value that is a function, since the function is a single value, different execution contexts can exist. The question is, how do we get the current execution environment from within a function when the same function is called in a different environment? Yes, this is designed to solve this scenario problem.

Summary: A collection of properties and behaviors aggregated together constitutes a basic object. An object can be instantiated using the new keyword, and the this pointer inside the object will vary depending on the execution environment. When calling object methods, you need to be aware of the orientation of this.

Object system

We talked about the composition of a base object. But in our actual development is far more complex than this, often is the nesting of multi-layer objects or multiple objects through a mapping file related to each other or an object inherited from another object… So as to build a larger object world and solve more complex application scenarios, we call this complex object object system, and this idea is called object-oriented programming

Explicit prototype

Concept: A default Prototype attribute on each function gives you the ability to add properties and methods to objects.

function people(name) { this.name = name; This.say = function () {console.log(' hello! I am ${name} `); }; } people. Prototype. Kungfu = function () {console.log(' I am ${this.name}, I am Chinese kungfu '); }; Const qad = new people(' qad '); Const zs = new people(' zS '); console.log(qad); console.log(qad.say()); console.log(qad.kungfu()); console.log(zs); console.log(zs.say()); console.log(zs.kungfu());Copy the code

The above code creates a people constructor, adds a name attribute and say method inside it, and a kungfu method on top of its prototype

How do you understand internal properties and stereotype properties?

Here we can use CSS styles to make it easier to understand

<p style="color:red" class="test"> </p>Copy the code

Above we created a tag and added an inline style and an external style to the tag. Aligned with the constructor, the inline style corresponds to the inner property, which is unique to the follower function, and the external style corresponds to the stereotype property, which can be public and used in multiple places.

This also avoids memory waste because each time a new constructor is created, the internal properties are regenerated, whereas the stereotype properties are not. And the prototype inheritance operation can be realized based on the prototype.

Constructor

Concept: Each object defaults to a Contructor and points to the constructor of the current prototype object.

console.log(qad.__proto__.constructor === people); // true
Copy the code

A picture is worth a thousand words

The constructor attribute points to the constructor function. The constructor attribute points to the constructor attribute

Implicit prototype (PROTO)

Concept: Each object has a _proto_ attribute that points to the prototype of the constructor that created the object.

console.log(qad.__proto__ === people.prototype); // true
Copy the code

Everything is an object, a function is an object, and as long as it’s an object, it has a _proto_ property, so _proto_ creates a link between the constructor and the prototype, finding the properties and methods of the prototype from the inside out of the constructor.

Prototype chain

When we create a constructor and access one of its properties. The constructor itself is searched first, then the explicit prototype is searched, then the implicit prototype is searched, then the __proto__ object is searched, until null. If there is a value, it will return the corresponding value, and if there is no value, it will return undefined. We call this process of searching from inside out prototype chain

A picture is worth a thousand words

Use object-oriented thinking

As mentioned above, we can use objects to model the real world and simplify complex problems. To make good use of the idea of object orientation, we need to keep in mind the three characteristics and several principles of object orientation

The three major characteristics

1: encapsulation

Chinese culture is extensive and profound, and it is easier to understand when the words are broken down

Seal: seal (seal up a set of behaviors, properties, business logic, and so on)

Package: Wrap (provide a container for storing sealed code, wrap it, export it)

There’s another concept of encapsulation called abstraction, which is easy to understand when you break it down (pulling out the “like” stuff)

Together, we take a bunch of similar attributes, behaviors, and logic and put them in a wrapper object that controls the input and output parameters for others to call. This is encapsulation.

2: inheritance

Follow: to continue (to continue)

To carry on (to carry on and carry forward)

Put together, the subclass continues to use the behavior or attributes of the parent class, and reasonably modify and expand the business, and output new objects. It’s quite a bit like taking over from his father.

3: polymorphism

: a variety of

State: state/form

In combination, the same instance object has different presentation forms in multiple states

Simple understanding is that a function with different input parameters, can get different output results

A few principles

1: Single responsibility principle

A class or a function to implement a single function, not messy, as pure as possible. Once a function becomes impure, multiple functions are implemented internally. When we use this function in multiple places, we tend to write a lot more compatibility code because it’s not pure enough.

2: Open and closed principle

A class should be open to extensibility and closed to modification. For example, if we encapsulate a function, we should make sure that there are enough holes for future iterations of new functions, rather than directly changing previously written code.

3: Richter’s substitution principle

Richter’s substitution principle is mainly used to restrict inheritance. A child class can extend the function of its parent class, but cannot change the original function of its parent class. If the subclass cannot completely implement the methods of the parent class, or some methods of the parent class have “distortion” in the subclass, it is recommended to disconnect the parent-child inheritance relationship and use dependency, aggregation, composition and other relationships to replace inheritance.

4: Dependence inversion principle

An upper-level module should not depend on a lower-level module; both should depend on its abstraction. In short, interface oriented development, each class provides an interface or abstract class, abstract class is usually relatively stable, when the low-level details change, should not directly affect the upper level. Details depend on abstractions, and as long as the abstractions do not change, the program does not change.

5: combination polymerization reuse principle

In code reuse, we should try to use association relations such as composition or aggregation to achieve, and then consider using inheritance to achieve.

6: high clustering and low coupling

As the name implies, highly similar things should be clustered together, and low similar things should not be coupled together

Js itself is an object-oriented programming language, in our daily development, every moment is enjoying the object-oriented programming experience brought to us.

Phase to recommend

I developed a chrome plugin to remind you to drink water.

Come on! Talk with Ed Qin about “problems” at work

Here are 20 new chrome extensions to share with you

Thank you

Welcome to pay attention to my personal public number front Qin Aide every day to push you fresh quality good article. Reply “benefits” and you will receive my carefully prepared front-end learning package. May you go all the way with light in your eyes!

Interested partners can also join my Qin Ai front end communication group, happy to play together!