Prototype definition: An object that provides shared properties to other objects. Prototype for short.
Look at the prototype with questions
- What is it?
- Why does it exist?
- Application?
- Advantages and disadvantages (precautions)?
- How to use?
A prototype,
1. What is the prototype
First give a definition: an object that provides shared properties to other objects, referred to as prototype.
All objects have an implicit reference, which is called the object’s prototype. When accessing an attribute of an object, it first looks for the attribute of the object itself, and if it fails to find it, it looks for its prototype object.
__proto__
& constructor
Concept introduction
- proto: Implicit prototype, the prototype of an object in the JS standard cannot be accessed directly by the property name, but most browsing is implemented
__proto__
Property to access the prototype of the object. - Constructor: constructor. When you create a function, you add a Prototype attribute to it, pointing to the prototype object, which automatically gets a constructor attribute called constructor, pointing back to the constructor associated with it.
2. The role of prototypes
Prototyping is a very important concept in Javascript, so what does it do?
The role is already mentioned in the definition: shared attributes
If an attribute cannot be found on an object, it will be searched on its prototype object, and so on until it is found, or if the end of the prototype chain is not found, the attribute does not exist; This feature allows any object created to have various methods in common, such as toString, hasOwnProperty, isPrototypeOf, etc
3. Prototyping
The shared attributes feature can be used to do a lot of clever things.
3.1 Attribute Delegation
The default methods on normal objects are methods from Object.prototype
const obj = {};
obj.toString();
Copy the code
3.2 Object-oriented (class) encapsulation
Javscript itself has no classes, and the classes in ES6 are little more than syntactic sugar wrapped in parasitic combinational packages.
function Person() {}
Person.prototype.name = 'tom';
Person.prototype.sayName = function() {
console.log(this.name);
};
const person1 = new Person();
person1.sayName(); // "tom"
Copy the code
3.3 inheritance
A subclass inherits attributes and methods from its parent class through stereotypes. Essentially, attribute methods that are not found on a subclass instance are found on a subclass’s prototype (an instance or stereotype of the parent class).
Inheritance in Javscript is not replication, but delegation. Delegate behavior means that some object (subclass) delegates the request to another object (superclass) when it can’t find an attribute or method reference.
function SuperType(){
this.name = 'tom';
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(){}
// The stereotype inherits SuperType
SubType.prototype = new SuperType();
const instance = new SubType();
instance.sayName()); // 'tom'
Copy the code
For a detailed introduction to Javascript inheritance, see my other article: Javascript Object-oriented & Inheritance
4. The advantages and disadvantages
advantages
- Space saving: Many of the methods on Object.prototype (toString, hasOwnProperty, isPrototypeOf, etc.) don’t need to be copied again and can be found and used through the prototype chain.
- High flexibility: Large degree of freedom
disadvantages
- Difficult to understand: other languages do not, the principle of the prototype is more complicated to investigate.
- Easy to override and modify: Stereotype attributes of reference types are shared by all instances, so changes are shared as well.
5. Precautions
Overrides and masking of attributes and methods can cause unexpected problems.
cover
Object.prototype.hasOwnProperty = function () {
alert('Ooops, method overwritten ');
return false;
}
const obj = {name: 'tom'};
console.log(obj.hasOwnProperty('name')); // The method on the prototype is masked
Copy the code
shielding
Because object attributes are searched first for the original object and then for the prototype, masking occurs when the object itself has attributes of the same name as those on the prototype.
function A() {
this.name = 'aaa';
}
A.prototype.name = 'a';
const instance = new A();
console.log(instance.name); // Attributes on the 'aaa' prototype are masked
Copy the code
function A() {
this.name = 'a';
this.sayName = ' ';
}
A.prototype.sayName = function () {
console.log(this.name);
};
const instance = new A();
instance.sayName(); // Methods on the 'aaa' prototype are masked
Copy the code
Second, prototype chain
What is a prototype chain
Definition: If you want to access a property that doesn’t exist in an object, look for the object associated with prototype inside the object. When an attribute is found, it is layered through, and the association actually defines a chain of archetypes.
The prototype chain will eventually point to Object.prototype, and the prototype chain will end at Object.prototype.__proto__ (null).
Prototype chain diagram
- Schematic diagram of prototype chain in inheritance:
Three, use,
Stereotype attribute judgment & setting
1. getPrototypeOf
Object.getprototypeof (obj) indirectly accesses the prototype Object of the specified Object.
Version: es6 +
2. setPrototypeOf
Object.setprototypeof (obj, obj1) indirectly sets the prototype version of the specified Object: ES6 +
3. hasOwnProperty
Properties that belong only to the object itself
The enumeration method
1. getOwnPropertyNames
Returns properties of all instances themselves. Version: es6 +
2. in
The IN operator returns true as long as it is accessible through the object, that is, if it exists on the object or prototype chain
3. for… in
Properties that can be accessed through an object and can be enumerated are returned, including instance and stereotype properties. Instance properties that mask the non-enumerable ([[Enumerable]] property is set to false) property in the stereotype will also be returned in the for-in loop because developer-defined properties are Enumerable by default.
4. Object.keys
All enumerable instance itself properties on an object.
5. Object.values
Returns the array version of the object value: ES8 +
const obj = {a: 1.b: '2'};
Object.values(obj); / / / 1, '2'
Copy the code
6. Object.entries
Returns the array version of the key/value pair: ES8 +
const obj = {a: 1.b: '2'};
Object.entries(obj); // [['a', 1], ['b', '2']]
Copy the code
7. Different enumeration methods
- Enumeration sequence
- The enumeration order of for-in loops and object.keys () is uncertain, depends on the JavaScript engine, and may vary from browser to browser.
- Object. GetOwnPropertyNames (), Object. GetOwnPropertySymbols () and the Object, the assign () enumeration sequence is deterministic. Enumerates numeric keys in ascending order, and then enumerates strings and symbolic keys in insertion order. Keys defined in object literals are inserted in their comma-separated order.
- Scope of the enumeration
- GetOwnPropertyNames, Object.keys, Object.values, Object.entries ranges are only properties/values of the instance itself
- In, for… In, Object.entries ranges are only properties/values of the instance itself