Program is an abstraction of the real world, a thing abstracted to the program becomes an object, in the world of the program, everything is an object.
Object-oriented programming means that all operations in a program are done through objects
Before you do anything, you need to find its object first, and then through the object to complete various operations
A thing usually consists of two parts: data and functionality
An object consists of two parts: properties and methods
The data of the thing goes to the object and is embodied in the attribute
The function of the thing to the object is embodied in the method
const user = { // Add attributes name: "seven", name: "seven", age:18, weight:100, // Add method get_info(){ (`Name:${},age:${},weight:${}`) }, set_age(age){ = age } }
Class calss
-
Creating Objects with Object.
- Inability to distinguish between different types of objects
- Inconvenient batch creation of objects
-
Creating objects by class
- Classes are object templates that allow you to define the properties and methods of an object directly in the class, and after defining them, you can create the object directly through the class
- Objects created through the same class we call like objects
- You can use instanceof to check if an object was created by a certain class
- We say that an object is an instance of a class if it was created by that class.
- Syntax.
calss class name {}
、const class name = claskk{}
- Creating Objects by Classes.
new class name()
class User { } // User() : Constructor const u1 = new User() (u1 instanceof User) // true
class property
class User {
name = "mickey" // instance attribute, only accessible via instance const u = new User()
static age = 18 // static attribute (class attribute), only accessible through the class.
}
// Use the new keyword to call the constructor User to create a new instance of the object, i.e. instantiate the object
const user = new User()
() // mickey
= "Beijing"
() // Beijing
class method
class User {
name = "mickey"
static age = 18
// Add method-instance method (not recommended)
sayHello = function (){
("hello world")
}
// Instance method, called by instance. method name (recommended)
printName(){
() // This is the current instance in the instance method.
}
// Static methods (class methods), called via class. MethodName
static test(){
() // Static methods where this points to the current class.
}
}
const user = new User()
()
()
()
constructor
class User {
// When the value of an instance attribute is specified directly in the class, all objects created will have this value for the attribute
name = "mickey"
}
class User {
// A special method constructor can be added to a class.
// This method is called a constructor.
// The constructor is executed when we call the class to create an object
// i.e. it is executed directly when the class is instantiated.
constructor(name,age) {
// You can assign values to instance attributes in the constructor, where this is the currently created object.
= name
= name
}
}
const u1 = new User("l",18)
(u1) // {name: 'l', age: 18}
const u2 = new User("q",28)
(u2) // {name: 'q', age: 28}
Encapsulation, Inheritance, Polymorphism
Three Object-Oriented Features: Encapsulation, Inheritance, and Polymorphism
seal inside
data security
An object is a container used to store different properties
Objects not only store attributes, they are also responsible for the security of the data
Properties that are added directly to an object are not safe because they can be modified arbitrarily
-
Privatized data
- Set the data to be protected as private and can only be used inside the class, attribute privatization add # in front of the attribute to indicate a private attribute, the
#name
- Set the data to be protected as private and can only be used inside the class, attribute privatization add # in front of the attribute to indicate a private attribute, the
-
Provide setter and getter methods to open up operations on data
- Obtaining and modifying private properties through methods provided inside the class
Modularity and Maintainability
Encapsulation can make code more modular by encapsulating related data and functionality in an object or module. This makes the code structure clearer and easier to understand and maintain
Uniform interfaces can be provided to access and manipulate data, ensuring that external code interacts with objects in a consistent manner.
For example, a well-encapsulated object can provide a set of methods to perform a specific operation, and the external code doesn't need to know the internal implementation details, it just needs to call those methods
class User {
// Private properties must be declared first
// Declare private attributes for assignment
#name = "q"
// Declare unassigned private attributes
#age
constructor(age) {
this.#age = age
}
getAge(){
return this.#age
}
getName() {
return this.#name // Get the private attribute name.
}
setName(name) {
if (name ! = null){
this.#name = name // Modify the private attribute name.
}
}
}
const user = new User(67)
(())
(())
()
Getting and setting private property values with getters and setters
class User {
#name
// getter gainnameattribute value
get name(){
return this.#name
}
// setter set upnameattribute value
set name(name){
this.#name = name
}
}
const user = new User()
= "l"
()
polymorphic
The type of the parameter is not checked in JS, so this means that any data can be passed as a parameter
To call a function, there is no need to specify the type, as long as the object meets certain conditions
Polymorphism provides us with flexibility
class User{
constructor(name) {
= name
}
}
const u1 = new User("l")
const u2 = new User("q")
function sayHello(obj){
("hello ",)
}
sayHello(u1)
sayHello(u2)
predecessor
Inheritance can be accomplished through the extends key
- When a class inherits from another class, it is equivalent to copying the code from the other class into the current class
- When inheritance occurs, the inherited class is called the parent class (superclass) and the inherited classes are called subclasses
- Inheritance reduces duplicate code and allows you to extend a class without modifying it.
class User{
constructor(name) {
= name
}
getInfo() {
()
}
}
// utilizationextendsKeywords. AdminpredecessorUserresemble
class Admin extends User{
}
const a = new Admin("l")
()
Inheritance allows you to extend a class without modifying it.
Object-oriented OCP Open-Closed Principle: Programs should be closed to modifications and open to extensions.
// Use the extends keyword. Admin inherits from the User class.
// In a subclass, you can override a method of the parent class by creating a method of the same name
class Admin extends User{
// Override the constructor
constructor(name) {
// When overriding a constructor, the first line of code in the constructor must be super()
super(name).
= name
}
// Override the getInfo method
getInfo(){
() // Call the getInfo method of the parent class via super
("Name is:",)
}
}
const a = new Admin("l")
()
object structure
There are actually two areas in the object where properties are stored:
the object itself
- Properties added directly through the object, located in the object itself
- Add attributes, methods in the form of key=value in the class, located in the object itself
Prototypes
There is also content in the object that is stored in other objects
object will have a property used to store the prototype object, which is called the
__proto__
The prototype object is also responsible for storing properties for the object
When we access properties in an object, we prioritize accessing the properties of the object itself, the
The object itself does not contain the attribute before going to the prototype object to find the
cases that will be added to the prototype object:
Methods added to a class by means of xxx(){} are located in the prototype
Properties or methods actively added to the prototype
class User {
name = "l" // store the object itself
get = function (){} // Store the object itself.
set(){} // Store the prototype object.
}
// The object itself
const user = new User()
prototype object data structure
// Access the prototype object
(user.__proto__)
// Access the prototype object
((user))
The data in the prototype object:
1. the data in the object (properties, methods, etc.), such as the () method
2. constructor (constructor of an object)
Prototype objects also have corresponding prototype objects that form a prototype chain, the length of which varies depending on the complexity of the objects
// Access the prototype object of the user object's prototype object
(user.__proto__. __proto__)
Prototype Chain:
- When reading an object's attributes, the object's own attributes are prioritized, the
- If it's in the object, use it; if not, go to the object's prototype and look for it.
- If it's in the prototype, it's used; if not, it goes to the prototype's prototype to find it.
- Until the prototype of the Object object is found (the prototype of Object has no prototype (is null))
- If it is still not found, it returns undefined
- Scope chain, is the chain to find the variable, it will report an error if it can't find it
- Prototype chain, is to find the attribute of the chain, can not find will return undefined
The role of prototypes
// All objects of the same type have the same prototype object, which means the prototype chain is the same for all objects of the same type
var u1 = new User()
var u2 = new User()
(u1.__proto__ === u2.__proto__) // true
-
All objects of the same type have a single prototype chain, and the prototype is the equivalent of a public area that can be accessed by all instances of that class by simply creating a
-
In the object some values are unique to the object, such as attributes, each object should have its own value, some values for each object are the same, like the various methods, for the same value there is no need to repeat the creation, such as the set () method, in the prototype, new100 objects will only be created 1 time, rather than creating 100 times
// For some methods that are independent of each object, you can use x=y to store them in the object's truth
class User {
get = function (){} // Store the object itself, creating one for each object.
set(){} // Stores the prototype object, shared by the prototype chain, so that multiple objects are not created over and over again.
}
- Inheritance in JS is realized through prototypes, when inheriting, the prototype of a subclass is an instance of the parent class.
// predecessorUser
class Admin extends User{
}
const a = new Admin()
// useran actual example --> object --> Objectoriginal form --> null
(a.__proto__.__proto__.__proto__.__proto__)
//() is a method in JavaScript for creating a new object whose prototype can be specified as an existing object.
/*
(proto, [propertiesObject])
proto: the prototype object of the newly created object, can be an existing object, if null, the newly created object has no prototype, and will not inherit any properties and methods.
propertiesObject (optional): object containing property descriptors, used to define the properties of the new object itself.
When the proto parameter is set to null, you can create an object without a prototype. Such an object is often used to store temporary data or to implement specific algorithms in order to avoid accidental access to properties in the prototype chain.
*/
const parent = {
sayHello() {
('Hello from parent')
}
}
const child = (parent)
()
// Create a new object with no prototype, defining a property called name with the value john, which is fully insured to be writable, enumerable, and configurable
const newObject = (null, {
name: {
value: 'John',
writable: true,
enumerable: true,
configurable: true
}
}).
Modify the prototype
In general, there is no need to modify the prototype object
/*
It is not recommended to modify the prototype through an instance of the class: it affects all objects of the same kind through one object.
*/
const a = new Admin()
const a1 = new Admin()
const a2 = new Admin()
// The set methods of the a, a1, and a2 objects are all changed
a.__proto__.set = () => {}
a2.__proto__ = new Base() // Doesn't affect the other objects, it's equivalent to assigning a new prototype object to the a2 object
pass (a bill or inspection etc)prototype
Modifying the prototype object
// Access the prototype object of the User instance
= () => {} // add a get method to all instances
Prototypes generally do not need to be modified, if you want to modify through the class.prototype to modify the
instanceof and hasOwn
// instanceof is used to check if an object is an instance of a class.
// Checks if there is an instance of the class in the object's prototype chain.
// Object is the prototype of all objects, so any instanceof operation with Object and Object will return true.
class User {
}
// Inherit User
class Admin extends User{
name = "l"
get(){}
set = function (){}
}
const admin = new Admin()
(admin instanceof Admin) // true
(admin instanceof User) // true
(admin instanceof Object) // true
// in is used to check whether an object contains a property in itself.
// Using the in operator to check a property returns true whether the property is in the object itself or in the prototype
("get" in admin) // true
// object.hasOwnProperty checks whether an object contains a property on its own (not recommended)
// hasOwnProperty is a method in the Object prototype.
(("name")) // true
(("set")) // true
(("get")) // false
// (object, property name) Used to check if an object contains a property on its own (recommended)
((admin, "name")) // true
((admin, "set")) // true
((admin, "get")) // false
old category
Classes were defined in early js through functions, which were a normal function if called directly, and a constructor if called through new
function User(name){
// In the constructor, this represents the newly created object.
= name
}
// Add properties (methods) to the prototype.
= function(){}
// Static properties
= "a"
// Static methods
= function(){}
User() // Normal function
const user = new User() // constructor
By creating classes the old way, the method attributes are more spread out and can be placed inside an immediately executable function
var User = (function () {
function User(name){
// In the constructor, this represents the new object.
= name
}
// Add properties (methods) to the prototype.
= function () {
}
// Static properties
= "a"
// Static methods
= function () {
}
const user = new User() // constructor
// Returns the User
return User
}
)()
const u = new User("l")
()
// inheritance of old classes
var User = (function () {
function User() {
}
return User
})()
var Admin = (function () {
function Admin() {
}
// predecessorUser,commander-in-chief (military)Userobject assigns a value toAdminprototype
= new User()
return Admin
})()
new operator
When using thenew When you call a function, it will be called as a constructor.
- Create a normal JS object (Object object {}), call it a new object
- Set the prototype attribute of the constructor to the prototype of the new object
- Use real parameters to execute the constructor and set the new object to this in the function
- If the constructor returns a non-primitive value, that value is returned as the return value of the new operation (never do this)
If the return value of the constructor is a raw value or no return value is specified, the new object will be returned as a return value
Return values are not usually specified for constructors
// 1. Create a normal JS object.
var newInstance = {}
// 2. Set the prototype property of the constructor to the prototype of the new object
newInstance.__proto__ =
// 3. Execute the constructor with the real parameter and set the new object to this in the function
constructor() {
// 4. If the constructor returns a non-primitive value, that value is returned as the return value of the new operation (don't do this)
// If the constructor returns a raw value or does not specify a return value, the new object is returned as the return value.
// Usually no return value is specified for a constructor.
}
Classification of objects:
built-in object
- Objects defined by the ES standard
- Object Function String Number ....
host object
- Objects provided by the browser
- BOM、DOM
Custom Objects
- Objects created by developers themselves