Reprinted from:Http://www.mangguo.org/javascript-prototype-inheritance-basic-mechanisms/
Due to language design, JavaScript does not have the concept of "class" in the true sense. The new command is usually used to instantiate an object. The essence of this language function depends on the prototype chain pattern unique to JavaScript.
So strictly speaking, JavaScript is a prototype-based object-oriented language. That is to say, each instance object has a prototype. The object inherits attributes and methods from the prototype.
1. Constructor
You can use constructors to create objects. The this keyword in the constructor points to the instance object itself:
- function People(name){
- this.name = name;
- }
Use the new operator and constructor to create an instance object:
- VaR people = new people ('xiaoming ');
- Console. Log (people. Name); // James
However, if two instances are created, they cannot directly share the attributes and methods:
- VaR people1 = new people ('xiaoming ');
- VaR people2 = new people ('wang ');
- People1.sex = 'male ';
- Console. Log (lele2.sex); // undefined
That is to say, once an object is instantiated, its attribute methods exist independently, and modifications to a property will not affect other instances.
2. Prototype
The prototype attribute is created automatically when an instance object is generated. It is an object and has attributes and methods that can be shared among instances. The attributes and methods of the instance are included in the constructor. In other words, the attributes and Methods inside the constructor become local attributes and methods after being instantiated, and the attributes and methods in prototype are only a reference in the instance, therefore, it can be shared by multiple instances.
Add the prototype attribute to the constructor just now:
- People. Prototype. Sex = 'female ';
- // Or write it as people. Prototype = {sex: 'female '};
- Console. Log (people1.sex); // male
- Console. Log (people2.sex); // female
The prototype attribute parameters of the People constructor directly affect the two instances of people1 and people2.
But why does people1.sex output male? This is because in Javascript, prototype relationships exist recursively. The prototype of an object is also an object, and the prototype itself may also have a prototype. The highest level of the prototype is the global object.
This means that once people1.sex is set to male, the corresponding value in the prototype cannot be exposed. If people1.sex has no value, it will be read from the prototype attribute of the constructor, and so on, first-level up lookup until the object.
NOTE: If "null" is used to assign a value to an object, you can destroy the custom object and release memory resources.