In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces JavaScript how to create classes and objects related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will have something to gain after reading this JavaScript article on how to create classes and objects, let's take a look.
1 JS object oriented
1.1 introduction to object-oriented programming
Process oriented programming
That is, POP (Process-oriented programming), process-oriented is to analyze the steps needed to solve the problem, and then use the function to realize these steps step by step, and then call them one by one in turn.
Object oriented programming
That is, OOP (Object Oriented Programming) object-oriented is to decompose the transaction into objects, and then divide and cooperate among the objects. In the idea of object-oriented program development, each object is a function center and has a clear division of labor. Object-oriented programming has the advantages of flexibility, code reusability, easy maintenance and development, and is more suitable for large-scale software projects with multi-person cooperation.
Object-oriented features: encapsulation, inheritance, polymorphism
The contrast between the two
Process oriented:
Advantages: the performance is higher than object-oriented, and it is suitable for things that are closely related to hardware, such as process-oriented programming used by single-chip microcomputer.
Disadvantages: no object-oriented easy to maintain, easy to reuse, easy to expand.
Object-oriented:
Advantages: easy to maintain, easy to reuse, easy to expand, because object-oriented has the characteristics of encapsulation, inheritance and polymorphism, we can design a low-coupling system, which makes the system more flexible and easier to maintain.
Disadvantages: performance is lower than process-oriented.
1.2 classes and objects in ES6
Introduction of object
In JavaScript, an object is an unordered collection of related properties and methods, and all things are objects, such as strings, numeric values, arrays, functions, and so on.
Objects are made up of properties and methods:
Attribute: the characteristic of a thing, represented by attributes in an object (a common noun).
Method: the behavior of things, represented by methods in objects (commonly used verbs)
Introduction of class class
The concept of a class has been added to ES6. You can declare a class using the class keyword, and then instantiate an object with this class.
Class abstracts the public part of an object, which generally refers to a large class (class)
An object refers to a specific object and instantiates a concrete object through a class.
Characteristics of object-oriented thinking:
Extract (abstract) attributes and behaviors shared by objects and organize (encapsulate) into a class (template)
Instantiate the class to get the object of the class
Create classes and objects
Class ClassName {
/ / class body
}
/ / create an instance:
Let obj = new ClassName ()
Constructor constructor of the class
The constructor () method is the constructor of the class (the default method), which is used to pass parameters, return the instance object, and is automatically called when the object instance is generated through the new command. If the definition is not displayed, a constructor () is automatically created for us inside the class.
/ / create a student class
Class Student {
/ / the constructor of the class
Constructor (uname, age, major) {
This.uname = uname
This.age = age
This.major = major
}
/ / add a method to the class
/ / write the method name and parentheses directly in the class
Sing () {
Console.log (this.uname + "can sing")
}
}
/ / instantiation of a class-create an object
Let peter = new Student ("Peter", 21, "CS")
Console.log (peter.uname); / / Peter
Peter.sing (); / / Peter can sing
Note:
Using the class keyword to create a class, we still habitually define the initial capitalization of the class name.
There is a constructor function in the class that accepts the passed parameters and returns the instance object.
The constructor function will automatically call this function whenever new generates an instance. If we do not write this function, the class will automatically generate this function.
Generating instance new cannot be omitted
Finally, pay attention to the syntax specification and create a class: do not add parentheses after the class name. Generate an instance: the class name is followed by parentheses, and the constructor does not need to add function
Static static member
Add a static to a member property or member method, and the member becomes a static member, which can only be called by this class
Class Person {
Static eat () {
Console.log ('eat')
}
}
Let p = new Person ()
Person.eat (); / / eat
P.eat (); / / error report
Cooperate with getter and setter
When a property has the get/set property, the property is the accessor property. Represents an additional operation on the return value when accessing the property or writing the property value. And this operation is the getter/setter function.
Getter: suitable for obtaining the attribute value of a member that needs to be dynamically calculated
Setter is a hint given when modifying an attribute.
Class Test {
Constructor (log) {
This.log = log
}
Get latest () {
Console.log ('latest was called')
Return this.log
}
Set latest (e) {
Console.log ('latest has been modified')
This.log.push (e)
}
}
Let test = new Test (['averse,' baked,'c'])
/ / A prompt will be given every time log is modified.
Test.latest ='d'
/ / every time you get the last element of log, latest, you can get the latest data.
Console.log (test.latest)
The above output:
Latest has been modified.
Latest was called.
['averse,' baked, 'crested,' d']
Inheritance of class
The extends keyword subclass inherits the parent class
The super keyword is used to access and call functions on the parent class of an object. You can call either the constructor of the parent class or the normal function of the parent class
The this in the class points to the problem: the this in constructor points to the instance object, and the this in the method points to the caller of the method.
Class Person {
Constructor (uname, age) {
This.uname = uname
This.age = age
}
}
Class Student extends Person {
Constructor (uname, age, major) {
/ / super passes the parameters of the subclass to the parent constructor to reduce the amount of code
Super (uname, age)
/ / subclasses can have their own unique properties
This.major = major
}
}
Let rick = new Student ("Rick", 22, "Mathematics")
Super calls parent ordinary functions
Class Parent {
SayHi () {
Return "Father: hello"
}
}
Class Child extends Parent {
SayHi () {
/ / super calls the parent ordinary function super.sayHi ()
Console.log (super.sayHi ())
}
}
Let man = new Child ()
Man.sayHi (); / / Father: hello
Object-oriented case
The basic architecture of the class:
Class Tab {
Constructor (id) {
/ / get related element nodes
/ / build the master node based on the id selector passed in
This.main = document.querySelector (id)
}
/ / initialize, bind each event
Init () {}
/ / Update the node and synchronize the entire status
UpdateNode () {}
/ / 1. Switching function
ToggleTab () {}
/ / 2. Add featur
AddTab () {}
/ / 3. Delete function
RemoveTab () {}
/ / 4. Modify function
EditTab () {}
}
Pay attention to:
When you bind an event in init (), if you don't need to execute it immediately, the event name is not followed by parentheses.
If you need the master node, declare a that variable and assign the value that = this in constructor ().
The insertAdjacentHTML () method: you can add a node string at the specified location of the specified element. (MDN insertAdjacentHTML)
AppendChild does not support appending child elements of a string. InsertAdjacentHTML supports appending elements of a string.
Node is a node, and when binding a node, you need to know in advance that there is a rebinding event on that node. You can use node & & node.click ().
Automatically execute an event without triggering it manually, using node.click (), node.blur (), and so on.
Double-click event: ondblick.
Double-click to disable text selection:
Window.getSelection? Window.getSelection () .removeAllRanges (): document.selection.empty ()
one
Double-click to disable text selection (CSS practice): user-select: none
2 constructor and prototype
2.1 Constructors and prototypes
Overview
In a typical OOP language (such as Java), there is the concept of class, the class is the template of the object, and the object is the instance of the class, but before ES6, the concept of class was not introduced in JS.
ES6, full name ECMAScript 6.0, 2015.06 edition. However, at present, the JavaScript of the browser is the ES5 version, and most high-end browsers also support ES6, but only some of the features and functions of ES6 are implemented.
Before ES6, objects were not created based on classes, but were defined with a special function called a builder function and their characteristics.
Constructor function
In JS, there are two things to keep in mind when using constructors:
Constructor is used to create a class of objects with uppercase initials
Constructors make sense only if they are used with new
New does four things when it executes:
Create a new empty object in memory.
Let this point to this new object.
Execute the code in the constructor to add properties and methods to the new object.
Return this new object (so you don't need return in the constructor).
Static members and instance members
Members can be added to the constructor of JS, either on the constructor itself or on the this inside the constructor.
Members that are added in these two ways are called static members and instance members, respectively.
Static members: members added to the constructor book are called static members and can only be accessed by the constructor itself
Instance members: object members created inside the constructor are called instance members and can only be accessed by instantiated objects
Function Human (uname, age) {
This.uname = uname; / / instance member
This.age = age; / / instance member
}
Human.x = 10; / / static member
Let rick = new Human ("rick", 35)
/ / console.log (rick.x); / / instantiated objects cannot call static members
Console.log (Human.x); / / static members can only be accessed by the constructor itself
This is the end of the article on "how JavaScript creates classes and objects". Thank you for reading! I believe you all have a certain understanding of "how to create classes and objects in JavaScript". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.