Explanation of js prototype
The constructor creates the object
function Person () {
}
var person = new Person();
person.name = 'Aditya';
console.log(person.name) // Aditya
Person is a constructor, we use new to create an instance object person
prototype
Every function has a prototype property.
Every JavaScript object (except null) will be associated with another object when it is created. This object is what we call a prototype, and each object will “inherit” properties from the prototype.
function Person () {
}
//Although it is written in a comment,
//but you should pay attention:
// prototype is a property that only functions have.
Person.prototype.name = 'Aditya' ;
var person1 = new Person();
var person2 = new Person();
console .log(person1.name) // Aditya
console .log(person2.name) // Aditya
proto
Every JavaScript object (except null) has a property called proto , which will point to the prototype of the object
function Person () {
}
var person = new Person();
console.log(person.__proto__ === Person.prototype); // true
constructor
Each prototype has a constructor attribute that points to the associated constructor instance. The prototype points to the constructor.
function Person() {
}
console.log(Person === Person.prototype.constructor); // truefunction Person() {
}
var person = new Person ();
console .log(person.__proto__ == Person.prototype) // true
console .log(Person.prototype.constructor == Person) // true
console .log( Object .getPrototypeOf(person) === Person.prototype) // true
Examples and prototypes
function Person () {
}
Person.prototype.name = 'Aditya';
var person = new Person ();
person.name = 'Daisy';
console.log(person.name) // Daisy
delete person.name;
console.log(person.name) // Aditya
In this example, we added the name attribute to the instance object person. When we print person.name, the result is naturally Daisy. But when we removed the person’s name attribute, read person.name, will not find the name attribute is the person. From the person from the person’s prototype object proto, which is a Person. prototype Look, fortunately, we Found the name attribute, the result is Aditya.