Wide sea diving, sky high the birds to fly. Hey hello! I'm Molly
Ten thousand people have ten thousand Hamlets in their hearts, and ten thousand developers have ten thousand understandings of object-oriented thinking. Here I will only briefly explain my understanding of object-oriented thinking.
basic concept
In the program, we use objects to build a model of the real world, simplify and provide access to functions that are otherwise difficult (or impossible) to use
This explanation is excerpted from MDN, and it is very confusing to read.
Here we can use the method to understand object-oriented, roughly saying that if it looks like a duck, then it is a duck. The difference between humans and machines is that humans have subjective consciousness and machines do not, a creature with a pointed mouth, a flat head, a quack cry and a swimming, then this is what we use object thinking to construct. A class of ducks. The machine will not be as subjective as a human to imagine that this is actually a big goose.
composition of objects
A basic object consists of several data types. If it is divided into large categories, it can be divided into lines, and attributes
Attributes: All data types can be considered as attributes of the object (the weight of the duckling, wings, feet, etc. are all attributes)
Behavior: generally refers to the function, giving the object ability (the duckling can swim, then the behavior of swimming is the ability of the duckling)
instantiated object
So far, we have created a duck class . At this time, the duck is only an initialization state, which is equivalent to being frozen. We need to unpack the duck, which can be instantiated using the new
keyword. So we get a brand new duck object.
new
keyword do? You can refer to the following code:
var obj = {};
//取得该方法的第一个参数(并删除第一个参数),该参数是构造函数
var Constructor = [].shift.apply(arguments);
//将新对象的内部属性__proto__指向构造函数的原型,这样新对象就可以访问原型中的属性和方法
obj.__proto__ = Constructor.prototype;
//取得构造函数的返回值
var ret = Constructor.apply(obj, arguments);
//如果返回值是一个对象就返回该对象,否则返回构造函数的一个实例对象
return typeof ret === "object" ? ret : obj;
this in the object
For the this
question, many beginners are confused by this this
point. In fact, to understand this
we only need to remember a sentence Who is calling it, it points to whom, this points 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
The data types in js are divided into basic data types and reference data types. Primitive data types are accessed by value, and reference data types are accessed by reference. The object puts all the references into the stack puts all the values into the heap . To obtain an object value, you need to first obtain the object reference, and then find the corresponding value according to the reference. If the value corresponding to the reference is a function, since the function is a single value, different execution contexts can exist. So the question is, the same function is called in different environments, how do we get the current execution environment inside the function? That's right, this
appeared to solve this kind of scene problem.
Summary: A bunch of properties and behaviors are aggregated together to form a basic object. An object can be instantiated through the new keyword. Due to the different execution environments, the this pointer inside the object is also different. When calling object methods, you need to pay attention to the problem of this pointing.
object system
We mentioned above, the composition of a basic object. But in our actual development, it is far more complicated than this, often the nesting of multi-layer objects or multiple objects are related to each other through a mapping file, or one object inherits from another object... so as to build a more Huge object world, to solve more complex application scenarios, we call this complex object object system , and call this idea object-oriented programming
Explicit prototype (prototype)
Concept: There is a default prototype property on every function that gives you the ability to add properties and methods to objects.
function people(name) {
this.name = name;
this.say = function () {
console.log(`hello!我是${name}`);
};
}
people.prototype.kungfu = function () {
console.log(`我是${this.name},我会中国功夫`);
};
const qad = new people('秦爱德');
const zs = new people('张三');
console.log(qad);
console.log(qad.say());
console.log(qad.kungfu());
console.log(zs);
console.log(zs.say());
console.log(zs.kungfu());
The above code creates a people
constructor, adds a name
property and say
method inside it, and adds a kungfu
method to its prototype
How does understand internal properties and prototype properties?
Here we can use the css
style to facilitate understanding
<style>
.test{
font-size:24px
}
</style>
<p style="color:red" class="test">哈哈</p>
We created a label above, and added an inline style and an external style to the label. If the constructor is aligned, the inline style corresponds to the internal attribute, which is unique to the follower function, and the external style corresponds to the prototype attribute, which can be public. Can be used in multiple places.
This also avoids wasting memory since every new
a new constructor is created, internal properties are regenerated, while prototype properties are not. And prototypal inheritance operations can be implemented based on prototypes.
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
A picture is worth a thousand words
Summary: Each function will have its own prototype, and the properties added to the prototype can be shared. The function is the object, and the object's own property constructor points to this constructor
Implicit prototype (proto)
Concept: Every object has a _proto_
property that points to the prototype of the constructor that created the object.
console.log(qad.__proto__ === people.prototype); // true
Everything is an object, and a function is also an object. As long as it is an object, it has _proto_
properties, so _proto_
establishes a connection between the constructor and the prototype, and finds the properties and methods of the prototype in the constructor from the inside out.
Prototype chain
When we create a constructor and access a property inside it. It will first look for the constructor itself, then the explicit prototype ( prototype
), then the implicit prototype ( __proto__
), then object
of __proto__
, until null
. If there is a value, it will return the corresponding value, if not, it will return undefined
. We call this inside-out search process prototype chain
A picture is worth a thousand words
Use object-oriented thinking
As mentioned above, we can use objects to build models of the real world and simplify complex problems. To use object-oriented thinking well, we need to keep in mind the three characteristics and principles of object-oriented
Three characteristics
1: Package
Chinese culture is broad and profound. After splitting the words, I found that it was better understood
Sealing: Sealing (sealing a series of behaviors, attributes, business logic, etc.)
Packaging: packaging (provide a container to store the sealed code, after packaging, external output)
There is also a concept in the package called abstract , which is easy to understand after splitting (extract the "like" thing)
The combination is: we extract a bunch of similar properties, behaviors, and logic, store them in a wrapper object, and control the input and output parameters for others to call. This is encapsulation.
2: Inheritance
continuation: continue (continue to continue)
Inherit: undertake
The combination is: the subclass continues to use the behavior or attributes of the parent class, and reasonably transforms and expands the business to output new objects. Quite a bit to inherit the father's business, and the meaning of the blue is out of the blue.
3: Polymorphism
many: many
state: state / form
The combination is: the same instance object has different display forms in multiple states
A simple understanding is that a function can get different output results through different input parameters.
a few principles
1: Single Responsibility Principle
A class or a function should implement a single function, not chaotic, the purer the better. Once the function becomes impure, multiple functions are implemented internally. When we use this function in multiple places, we often write a lot of compatible code because it is not pure enough.
2: The principle of open and closed
A class should remain open for extensibility and closed for modification. For example, if we encapsulate a function, we should try to reserve a good opening so that new functions can iterate in the future, and avoid directly changing the code that has been written before.
3: The Liskov Substitution Principle
The Liskov substitution principle is mainly used to constrain inheritance. A subclass can extend the functions of the parent class, but cannot change the original function of the parent class. If the subclass cannot fully implement the parent class method, or some methods of the parent class have been "distorted" in the subclass, it is recommended to break the parent-child inheritance relationship, and use dependencies, aggregation, composition and other relationships to replace inheritance.
4: Dependency Inversion Principle
Upper-level modules should not depend on lower-level modules, both should depend on their abstractions. In short, it is interface-oriented development. Each class provides interfaces or abstract classes. Abstract classes are often relatively stable. When the lower-level details change, they should not directly affect the upper layer. The details depend on the abstraction, and as long as the abstraction remains the same, the program should not change.
5: Principles of combination, aggregation and reuse
When reusing code, try to use association relationships such as composition or aggregation to implement it first, and then consider using inheritance relationships to implement it.
6: High clustering and low coupling
As the name suggests, things that are highly similar should be clustered, and things that are low-similar should not be coupled together
js itself is an object-oriented programming language. In our daily development, we are enjoying the programming experience that object-oriented brings us all the time.
grateful
Welcome to pay attention to my personal public number Click to view: There are tricks in the front end to push you fresh and high-quality good articles every day. Reply to "welfare" to get the front-end knowledge spree I carefully prepared. May you go all the way with light in your eyes!
Interested friends can also add me Click to view: WeChat: yuyue540880 Pull you into the group, exchange front-end technology together, and play together!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。