Objects need to be categorized
Reason 1: There are many objects with the same properties and behavior, so we need to classify them into the same class, such as square1 and square2, so that it is easy to create similar objects.
2. There are many objects with other attributes and behaviors, so different categories are needed. For example, Square/Circle/Rect is different, Array/Function is different, and Object created is the most featureless Object.
Type V.S. class
Number/string/bool/symbol/null/undefined/object
Class is the classification of objects, there are countless kinds, common Array Array/Function/Date and so on.
There are two ways to define classes
1. Use constructors (combined with prototypes)
A constructor is a function specifically used to create an object. Start by creating a constructor that uses the this keyword inside to refer to the instance object.
function Square(width) {
this.width = width
}
Copy the code
Define the common properties on the constructor’s Prototype object.
Square.prototype.getArea = function() {
return this.width * this.width
}
Square.prototype.getLength = function() {
return this.width * 4
}
Copy the code
Use new to generate instance objects.
let square1 = new Square(5)
square1.getArea() / / 25
square1.getLength() / / 20
Copy the code
In JS, all functions have a Prototype property when they are defined, and in Prototype the default constructor property is the function itself.
Constructor X
- The X function itself is responsible for adding attributes to the object itself
X.prototype
Object is responsible for holding the shared properties of the object
New operator
The new operator creates an instance of a user-defined object type or of a built-in object with a constructor.
new X()
It does four things automatically:
- Automatically creates an empty object
- Automatically associate a stereotype with an object whose address is specified as
X.prototype
- Automatically treats empty objects as
this
Keyword run constructor - automatic
return this
Code specification
On case:
- All constructors begin with a capital letter
- All constructed objects begin with a lowercase letter
About
- Functions after new, using the noun form, such as new Person(), new Object()
- Other functions usually start with a verb, such as createSquare(5), createElement(‘div’)
2. Use the class
class Square{
// Use the constructor method to add attributes
constructor(width){
this.width = width
}
getArea(){
return this.width * this.width
}
getLength(){
return this.width * 4}}let square1 = new Square(5)
square1.getArea() / / 25
square1.getLength() / / 20
Copy the code
Constructor is a constructor used to create and initialize an object created by class. A class can have only one special method named “constructor”.