4. Constructor + prototype assemble a class directly; the same constructor will assemble the same type
The previous few learned that JavaScript writing classes were based on constructors and prototypes. In that case, we write a tool function to write the class.
Copy Code code as follows:
/**
* $class Write one of the class tool functions
* @param {Object} constructor
* @param {Object} prototype
*/
function $class (constructor,prototype) {
var c = Constructor | | function () {};
var p = Prototype | | {};
C.prototype = p;
return C;
}
Well. The tool class is written to assemble: Use the constructor to generate the properties (fields) of the class instance, and the method that the prototype object uses to generate the class instance.
Copy Code code as follows:
Constructors
function person (name) {
THIS.name = name;
}
Prototype Object
var proto = {
Getname:function () {return this.name},
Setname:function (name) {this.name = name;}
}
Assembly
var man = $class (Person,proto);
var Woman = $class (Person,proto);
OK, this time you've got two classes of Man,woman. and is of the same type. The test is as follows:
Copy Code code as follows:
Console.log (man = = Woman);//true
Console.log (Man.prototype = = Woman.prototype);//true
To create an object look,
Copy Code code as follows:
var mans = new Man ("Andy");
var woman = new Woman ("Lily");
Console.log (Mans instanceof Man);//true
Console.log (woman instanceof woman);//true
Console.log (mans instanceof person);//true
Console.log (woman instanceof person);//true
Ok everything as we expected. But there is a problem, the result of the following code output false,
Copy Code code as follows:
Console.log (Man.constructor = = person);//false
This is unpleasant: from the above code to see that man is indeed the new man ("Andy") through the man class, then the constructor for the object instance man should point to man, but why does it backfire?
The reason is that $class has rewritten the person's prototype: C.prototype = P;
OK, so we're going to put the $class slightly rewritten and hang the method on the constructor's prototype instead of overriding the constructor's prototype, as follows:
Copy Code code as follows:
function $class (constructor,prototype) {
var c = Constructor | | function (){};
var p = Prototype | | {};
//C.prototype = p;
for (Var ATR in P)
C.prototype[atr] = P[atr];
return C;
}