What is a Prototype?
Javascript states that each function has a Prototype object attribute that points to another object (above the prototype chain).
What is a prototype chain?
A “chain” that follows a prototype object to find an object is called a prototype chain:
function Person(name,age){
this.name = name
this.age = age;
}
let me = new Person("chao"."9");
console.log(me.toString());
Copy the code
Where did ME. ToStirng come from?
- In looking for me
toString
methods - Obviously not in me, so go ahead
me.__prote__
In looking for me.__proto__
No, then gome.__proto__.__proto__
In looking for- while
me.__proto__.__proto__
There is onetoString
You can look at the structure of me
The whole process is around a __proto__ object, so it is called a prototype chain (if num.__proto__.__proto is not there, it will continue to find __proto__ at the next level until it finds toString).
① The __proto__ attribute is unique to the object
The prototype attribute is unique to functions (functions are also objects, so __proto__).
Unlike other programming languages, JavaScript allows each object instance to have a common object (method, property) through prototype objects.
We add methods to an object in two ways:
Constructor adds:
function Person(name,age){
this.name = name
this.age = age;
this.sayHello = () = > console.log("Hello,my name is " + this.name);
}
let me = new Person("chao".9);
let tom = new Person("Tom".32);
console.log(tom.sayHello == me.sayHello);
Copy the code
Prototype added:
function Person(name,age){
this.name = name
this.age = age;
}
// Lambda expressions can't get this (in the above example this comes from the parent scope)
Person.prototype.sayHello = function(){console.log("Hello,my name is " + this.name)};
let me = new Person("chao".9);
let tom = new Person("Tom".32);
me.sayHello();
Copy the code
The output added using the constructor is False while the prototype adds True. You can assume that objects added with stereotypes are the same in each instance.
Prototypes are a unique and superior aspect of JavaScript. It effectively optimizes the memory footprint of objects because each method is common.
You can add any object to Prototype and access it via obj.any:
function Person(name,age){
this.name = name
this.age = age;
}
// Add the gender attribute
Person.prototype.gender = "Unknown";
// Add sayHello constructor
Person.prototype.sayHello = (name) = > console.log("Hello,my name is " + name);
// Add the Person constructor
Person.prototype.Constructor = Person;
let me = new Person("chao".9);
me.gender = "Male";
console.log(me.gender);
me.sayHello(me.name);
let son = new me.Constructor("son"."0");
console.log(son.name);
Copy the code
Output:
Hello,my name is Chao SonCopy the code
It feels like adding an object to Prototype should be designed as a method, like Add(obj). Obj.prototype. any = o
Of course, maybe MY level is low, ha ha ha 😂
Study hard! ✊