& Nbsp; at the beginning of this article, we will record some write-class tool functions. Through the previous article, we know that they are essentially constructor + prototype. I am not afraid to understand the various writing methods it encounters. & Nbsp; constructor + prototype directly assemble a class; the same constructor will group the same type of viewsourceprint? 01/* SyntaxHighlighter. al
At the beginning of this article, we will record some tool functions for writing classes. Through the previous article, we know that they are essentially constructors + prototypes. I am not afraid to understand the various writing methods it encounters.
Constructor + prototype directly assemble a class; the same constructor will group the same type
View sourceprint? 01 /**
02 * $ one of the class Writing Tool Functions
03 * @ param {Function} constructor
04 * @ param {Object} prototype
05 */
06 function $ class (constructor, prototype ){
07 var c = constructor | function (){};
08 var p = prototype | | {};
09 c. prototype = p;
10 return c;
11}
The constructor is used to generate the attributes (fields) of the class instance. The prototype object is used to generate the class instance method.
View sourceprint? 01 // Constructor
02 function Person (name ){
03 this. name = name;
04}
05 // prototype object
06 var proto = {
07 getName: function () {return this. name },
08 setName: function (name) {this. name = name ;}
09}
10 // assemble
11 var Man = $ class (Person, proto );
12 var Woman = $ class (Person, proto );
At this time, two classes of Man and Woman are obtained. And is of the same type. The test is as follows:
View sourceprint? 1 console. log (Man = Woman); // true
2 console. log (Man. prototype = Woman. prototype); // true
Create an object
View sourceprint? 1 var man = new Man ("Andy ");
2 var woman = new Woman ("Lily ");
3
4 console. log (man instanceof Man); // true
5 console. log (woman instanceof Woman); // true
6 console. log (man instanceof Person); // true
7 console. log (woman instanceof Person); // true
OK. Everything is as expected. However, the following code outputs false.
View sourceprint? 1 console. log (man. constructor = Person); // false
This is unpleasant: From the code above, we can see that man is indeed var Man = new man ("Andy") from the new Man class, so the man constructor of the object instance should point to Man, but why is it counterproductive?
The reason is that the prototype of Person is rewritten in $ class: c. prototype = p;
Well, we will slightly rewrite $ class and link all methods to the constructor prototype (instead of rewriting the constructor prototype), as shown below:
View sourceprint? 1 function $ class (constructor, prototype ){
2 var c = constructor | function (){};
3 var p = prototype | | {};
4 // c. prototype = p;
5 for (var recognition in p ){
6 c. prototype [recognition] = p [recognition];
7}
8 return c;
9}