JS knowledge
The constructor
Constructors in ECMAScript are used to create objects of a specific type. Create custom classes that define properties and methods for their object types in the form of functions.
Different from normal functions: constructors are usually capitalized and called with new.
Use of the 🌰 constructorfunction Person(name, sex, age) {
this.name = name
this.sex = sex
this.age = age
this.eating = function() {
console.log(this.name + 'At dinner')}}let zhangsan = new Person('Joe'.'male'.18)
console.log(zhangsan) // Person{name: 'zhang3 ', sex:' male ', age: 18, eating: [Function (anonymous)]}
console.log(zhangsan.name) / / zhang SAN
console.log(zhangsan.eating()) // Zhang SAN is having dinner
Copy the code
Above we create a constructor named Person and create an instance object named Zhangsan.
The difference between a constructor and a normal function when executed:
The biggest difference is that when the function is executed, the constructor creates an instance object, to which this refers.
Prototype and prototype chain
We talk about JS object oriented element when inheritance, so JS is how to achieve inheritance?
JS relies on prototype chains to implement inheritance
The inheritance relationship is actually a chain relationship, and the starting point of this chain in JS is NULL.
And to form a chain, we all know that a child has to know who its parent is to be associated with it. Prototype and __proto__ are associated with this relationship, we call them “prototype”, and according to the prototype of this kind of chain relationship, called the prototype chain.
The prototype and __proto__
- Most functions (especially constructors) have a prototype property built in. The value of the prototype property is an object that stores properties and methods that are “public” to be called by the instance to which the current class belongs
- Arrow functions have no prototype attribute
- On the prototype object there is a built-in property constructor, whose value is the current function itself
- Each object has a built-in __proto__(stereotype “implicit stereotype”) attribute that points to the prototype object of its class
- Prototype This Object’s __proto__ value is null because Object is the “base class” of all objects.
🌰
When we create an array, there is no split, forEach… That’s why our array can use them directly. It’s because of the prototype chain.
let arr = [10.20.30]
Copy the code
We let an Array arr, which is equivalent to creating an Array instance object for the Array class (constructor) in JS. Each object has its own __proto__ pointing to the class it belongs to. When we use concat, push, etc., first JS will look in the private property, When he finds that he doesn’t have the property or method, he looks for it in his parent, array. prototype, finds it, calls it, doesn’t find it, then goes up the prototype and repeats until he finds null.