js object classification
other
1. Recommended articles
You can't class, but you must learn prototype
What exactly does JS new do?
What is the significance of proto and prototype in JS?
ES6 all new features
2. A constructor is a function that can construct an object
3. Encapsulation: write the details into a function. Others only need to call the function and pass a parameter (width)
4. Functions are also objects
5. In order for new to run, the father of JS specifies in advance:
All functions in js have their own prototype attribute.
The prototype property has its own constructor.
The value of constructor is equal to the function itself.
6. Relationship between common attributes and prototypes: include and be included.
The entire object with common properties is called a prototype.
The address of the object is the address of the prototype, and each attribute in it is called a common attribute.
Do objects need to be classified?
Requirements: output the area and perimeter of various shapes
square The analysis square has three properties:Side length, area and perimeter let square={ width:5, getArea(){ return this.width * this.width }, getLength(){ return this.width * 4 } }
A dozen squares
let squareList=[] for(let i=0;i<12;i++){ squareList[1]={ width:5, getArea(){ return this.width * this.width }, getLength(){ return this.width * 4 } } }
What if the width is not all 5?
let squareList=[] let widthList=[5,6,7,8,5,6,7,5,5,4,5,6] for(let i=0;i<12;i++){ squareList[i]={ width:widthList[i], getArea(){ return this.width * this.width }, getLength(){ return this.width * 4 } } }
Garbage code, waste too much memory.
With the help of the prototype, the common properties of 12 objects are put into the prototype
let squareList=[] let widthList=[5,6,7,8,9,5,6,7,8,9,5,6] let squarePrototype={ getArea(){ return this.width * this.width }, getLength(){ return this.width * 4 } } for(let i=0;i<12;i++){ squareList[i]=Object.create(squarePrototype) squareList[i].width= widthList[i] } Console input: squareList
It's still garbage code. The code of the created square is too scattered.
Then code the code to a function and call the function.
Extract to function
let squareList=[] let widthList=[5,6,7,8,9,5,6,7,8,9,5,6] function createSquare(width){//This function is called a constructor. A constructor is a function that can construct an object let obj=Object.create(squarePrototype)//Create an empty object based on squarePrototype obj.width=width return obj } let squarePrototype={ getArea(){ return this.width * this.width }, getLength(){ return this.width * 4 } } for(let i=0;i<12;i++){ squareList[i]=createSquare(widthList[i]) //Encapsulation, write the details into a function. Others only need to call the function and pass a width. }
The square prototype and the createSquare function are still scattered. Can they be combined?
A function is also an object. Is it more compact to put the prototype on a function?
let squareList = [] let widthList = [5,6,5,6,5,6,5,6,5,6,5,6] //Declare the createSquare function, which creates a square object function createSquare(width){ let obj = Object.create(createSquare.squarePrototype) // Use before define? NO This code is calling createSquare Will be executed obj.width = width return obj } createSquare.squarePrototype = { //Is it tight enough to put the prototype on the function? getArea(){ return this.width * this.width }, getLength(){ return this.width * 4 }, constructor: createSquare //It is convenient to find the constructor through the prototype (and put the constructor on the prototype) } for(let i = 0; i<12; i++){ squareList[i] = createSquare(widthList[i])//createSquare is called here console.log(squareList[i].constructor) // constructor can know who constructed this object: who's your mother? }
In addition to putting the prototype on the constructor, you also put the constructor on the prototype.
After getting the function, you can easily find its prototype, or you can easily find its function by getting the prototype.
This code is almost perfect. Why not fix it and let every js developer use it directly
new operator, let's feel the love of the father of js
Function and prototype combination (Rewriting)
let squareList = [] let widthList = [5,6,5,6,5,6,5,6,5,6,5,6] function Square(width){ this.width = width } Square.prototype.getArea = function(){ //Set common property (getArea) return this.width * this.width } Square.prototype.getLength = function(){ return this.width * 4 } for(let i = 0; i<12; i++){ squareList[i] = new Square(widthList[i]) console.log(squareList[i].constructor) } // How beautiful, there is hardly a redundant nonsense // Each function has a prototype attribute, which is intentional by the father of JS // Each prototype has a constructor attribute, which is also intentional
In order for new to run, the father of js specifies in advance:
All functions in js have their own prototype attribute, and the prototype attribute has its own constructor. The value of constructor is equal to the function itself.
example
function f1(){}
console.dir(f1)
Console input: F1 prototype. constructor === f1
Output result: true
1. Create your own object and point the prototype of the object to the prototype with getarea and getlength.
Now new will do it for us
2. Use this to represent the new object
3. There's no need to write return. new will do it for us
4. An object with common attributes will be created before.
Now you need to add one by one. Because prototype already has a constructor attribute, square Prototype = a new object will cause the constructor to be lost.
So the best way is to add attributes to the prototype. You can also use object Assign plus.
summary
1.new X() does four things automatically
Automatically create empty objects
Automatically associate the prototype for the empty object, and the prototype address is X.prototype
Automatically run the constructor with an empty object as the this keyword
Auto return this
– this is the love of the father of JS
2. Constructor X
The X function itself is responsible for adding attributes to the object itself
10. The prototype object is responsible for saving the common properties of the object
example
function Dog(name){ this.name=name this.color='white' this.king='Samoye' } Dog.prototype.wangwang=function(){console.log('Woof')} Dog.prototype.run=function(){console.log('The dog is running')} let dog1=new Dog('Xiaobai') Console input: dog1 Output results: Dog {name: 'Xiaobai', color: 'white', king: 'Samoye'} Console input: dog1.wangwang() Output result: Wang Wang Console input: dog1.run() Output: the dog is running
this refers to the new object dog1 that has not been created yet
Code specification
1. Case
All constructors are capitalized
function add(x,y){return x+y} //Not a constructor, no uppercase function Dog(name){this.name=name}
All constructed objects, initial lowercase
let dog1=new Dog()
2. Part of speech
(1) The function after new uses the noun form
Such as new Person(), new Object()
(2) Other functions generally start with verbs
Ordinary functions usually use verbs
For example, createSquare(5) and createElement('div ')
function createSquare(width){...}
Other rules will be discussed later
problem
1. How to determine how many parameters to pass?
function Square(width){...}
Write your own words clearly. But if it is a constructor provided by others, how do I know to accept several parameters?
let arr1=new Array(3)
Is the array 3 or an array of length 3?
Only documents can be viewed 🔍 mdn array
new Array(element0,element1 [,... [, elementN]]) / / multiple parameters are the elements in it
new Array(arrayLength) / / one parameter is the length of the array
js is the only formula
How to determine the prototype of an object?
1. Why
The prototype of let obj=new Object() is object prototype
The prototype of let arr=new Array() is array prototype
The prototype of let square=new Square() is square prototype
The prototype of let fn=new Function() is function prototype
2. This is deliberately done because of the new operation
conclusion
The prototype corresponds to what is behind new prototype
Who constructed your prototype is the object corresponding to whose prototype attribute
Prototype formula
Object proto = = = its constructor prototype
The two prototype addresses are the same!
Exercise 1
let x={}
What is the prototype of 1.x? x.__proto__ What is the value of? Are the above two questions equivalent?
let x=new Object{}
x.proto=Object.prototype
So the prototype of x is object Prototype this object
x.__proto__ The stored address is its prototype
2. Draw all the attributes of x in memory
Exercise 2
let square=new Square(5)
1. What is the prototype of square? square.__proto__ What is the value of?
square.proto=Square.prototype
2. Draw all the properties of square with memory, omitted
Exercise 3
1.Object. Which function is prototype constructed from?
I don't know. It has no father and no mother
2.Object. What is the prototype of prototype?
No prototype
3.Object.prototype.proto?
null
4. Draw the above contents in memory, omitted
The constructor of all Function objects is Function
window. If Function is a Function object, the constructor of this "Function object" is Function;
window. If object is a Function object, the constructor of this "Function object" is Function;
window. If function is a function object, the name of this "function object" is__ proto__ Yes (object. Proto = = its constructor. prototype)
The final version of Square (in doubt) can be further optimized. We'll talk about it later.
Objects need to be classified
Write another circle with the constructor
function Circle(radius){ this.radius = radius } Circle.prototype.getArea=function(){ return Math.pow(this.radius,2) * Math.PI } Circle.prototype.getLength=function(){ return this.radius * 2 * Math.PI } let c1=new Circle(10)//Declare a new circle Console input: c1.radius Output result: 10 Console input: c1.getArea() Output result: 314.1592653589793 Console input: c1.getLength() Output result: 62.83185307179586
Then another rectangle
function Rect(width,height){ this.width = width this.height=height } Rect.prototype.getArea=function(){ return this.width * this.height } Rect.prototype.getLength=function(){ return (this.width+this.height)*2 } let r1=new Rect(4,5) //Declare a new rectangle Console input: r1 Output results: Rect {width: 4, height: 5} Console input: r1.getArea() Output result: 20 Console input: r1.getLength() Output result: 18
Do objects need to be classified?
Need classification
Reason one
Many objects have the same properties and behaviors, and they need to be divided into the same class
Such as square1 and square2, it is convenient to create similar objects
Reason 2
However, many objects have other properties and behaviors, so different classifications are required
For example, Square/circle/Rect are different classifications
Array/Function is also classified differently
The Object created by Object is the most featureless Object.
Type VS class
type
Types are the classification of JS data. There are 7 types (4 bases, 2 empty objects and 1 object)
class
Class is a classification of objects. There are countless kinds
Common are Array, Function, Date, RegExp, etc
object is the least characteristic class. Now let's look at the characteristic classes
The first Array object
1. Define an array
let arr=[1,2,3] / / abbreviation
let arr=new Array(1,2,3) / / elements are 1, 2, 3
let arr=new Array(3) / / length is 3
When you focus on an object, you mainly look at its own attributes and common attributes
2. Self attributes of array objects
Its own attributes are: '0' /'1 '/'2' /'length '
Note: the property name has no numbers, only strings. All in the array are strings, not numbers!
3. Common properties of array objects
Common attributes include 'push' / 'pop' / 'shift' / 'unshift' / 'join'
The usage is in MDN, and these API s will be taught separately later
Array objects have more common attributes than ordinary objects
The second Function object
1. Define a function
function fn(x,y){return x+y}
let fn2=function fn(x,y){return x+y}
let fn=(x,y)=>x+y
let fn=new Function('x ',' y ',' return x+y ') / / important
2. Function object attributes
'name'/'length'
example
let fn = new Function('x', 'y', 'return x+y') console.dir(fn)
3. Common attributes of function objects
'call'/'bind'/'apply'
Functions will be introduced separately later
JS ultimate question
1. Who built the window?
Window (upper case)
So window proto === Window. prototype
2.window. Who constructed the object?
window.Function
Because all the functions are window Function constructed
3.window. Who constructed the function?
window.Function
Because all the functions are window Function constructed
Construct yourself? No, it's God's arrangement
The browser constructs a Function and then specifies that its constructor is itself
window.Function.constructor === window.Function
es6 new syntax class
Some front ends think that prototype is outdated. I think the opposite, but I still have to learn class anyway.
Prototype or class? Are used to classify objects
prototype syntax
function Square(width){ this.width = width } Square.prototype.getArea = function(){ //Set common property (getArea) return this.width * this.width } Square.prototype.getLength = function(){ return this.width * 4 }
class syntax
The parameter to be accepted (width) is written to the constructor, indicating that it is a constructor
class Square{ constructor(width){ this.width=width } } getArea(){ return this.width * this.width } getLength(){ return this.width * 4 }
class syntax introduces more concepts
class Square{ static x = 1 //The first concept Attribute (x) is Square, Square X to use X width = 0 //The second concept Initialize this Width (the default width is 0) constructor(width){ this.width=width } } getArea(){ return this.width * this.width } getLength(){ return this.width * 4 } get area2(){ //The third concept Read only attribute, you can write getArea() as get area2(). The difference is that there is no need to add parentheses () when calling area2 return this.width * this.width }
Rewrite Circle with class
class Circle{ constructor(radius){ this.radius = radius } getArea(){ return Math.pow(this.radius,2) * Math.PI } getLength(){ return this.radius * 2 * Math.PI } } let circle = new Circle(5) circle.radius circle.getArea() circle.getLength() circle.getLength()
Novice advice
1. How to learn so many new grammars
1 'read all the MDN class documents and write them down
T use it to learn, practice to learn, remember better
All new syntax for ES 6
The new syntax for classes and objects is class,Object initialization and Destructuring assignment
The difference between two function writing methods in class
Grammar 1
class Person{ sayHi(name){} //Equivalent to sayHi: function(name){} //Note that in general, we do not use arrow functions in this syntax } //Equivalent to function Person(){} Person.prototype.sayHi = function(name){}
Syntax 2: notice that the colon becomes the equals sign
class Person{ sayHi = (name)=>{} // Note that in general, we do not use ordinary functions in this syntax, but more arrow functions } //Equivalent to function Person(){ this.sayHi = (name)=>{} }
Note: do not force full conversion to ES5
Most class grammars can be converted to ES5 grammars, but not 100% can be converted. Some class grammars can be understood by you and do not need to be forcibly converted to ES5.
Class is to declare a class, which is used to create objects. You just need to write it according to this syntax.
If you want this object to have some properties, write it to the constructor.
If you want this object to have some functions, write it outside.