6. Writing Method of Prototype. js
Copy codeThe Code is as follows:
// Code in prototype. js
Var Class = {
Create: function (){
Return function (){
This. initialize. apply (this, arguments );
}
}
}
// Simplified
Function Clazz (){
Return function (){
This. initialize. apply (this, arguments );
}
}
Follow these steps to write a class,
Copy codeThe Code is as follows:
// Class name Person
Var Person = Class. create ();
// Define Person through prototype Rewriting
Person. prototype = {
Initialize: function (name ){
This. name = name;
},
GetName: function (){
Return this. name;
},
SetName: function (name ){
This. name = name;
}
}
// Create an object
Var p = new Person ("jack ");
Console. log (p. constructor = Person); // false
Initialize initializes the object (equivalent to the constructor) and writes down the methods in sequence.
If there is a problem, we can see that p. constructor = Person is false, which is a small defect of Prototype. js. The reason is that the prototype of Person is rewritten. To enable the constructor to point to the correct constructor, you only need to maintain the constructor attribute during prototype rewriting.
Copy codeThe Code is as follows:
Person. prototype = {
Constructor: Person, // note this
Initialize: function (name ){
This. name = name;
},
GetName: function (){
Return this. name;
},
SetName: function (name ){
This. name = name;
}
}
All right, p. constructor = Person is true.