4. Constructor and prototype directly assemble a class; the same constructor will assemble the same type
From the previous articles, we know that writing classes in JavaScript is nothing more than constructor and prototype. In this case, we write a tool function to write the class.
/**
* $class is one of the class writing tool functions
* @param {Object} constructor
* @param {Object} prototype
*/
function $class(constructor,prototype) {
var c = constructor || function(){};
var p = prototype || {};
c.prototype = p;
return c;
}
Hmm. The tool class is written, let’s assemble it: use the constructor to generate the attributes (fields) of the class instance, and the prototype object is used to generate the methods of the class instance.
//Constructor
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, now we have obtained two classes of Man and Woman. And it's the same type. The test is as follows:
console.log(Man == Woman) ;//true
console.log(Man.prototype == Woman.prototype);//true
Create the object and see,
var man = new Man("Andy");
var woman = new Woman("Lily") ;
console.log(man instanceof Man);//true
console.log(woman instanceof Woman);//true
console.log(man instanceof Person);//true
console .log(woman instanceof Person);//true
ok everything is as we expected. But there is a problem. The result of the following code outputs false,
console.log(man.constructor == Person);//false
This is unpleasant: from the above code, we can see that man is indeed created through the Man class new var man = new Man ("Andy"), then the constructor of the object instance man should point to Man, but why does it backfire?
The reason is that the prototype of Person is rewritten in $class: c.prototype = p;
Okay, let’s rewrite $class slightly and hang all the methods on the prototype of the constructor (instead of rewriting Write the prototype of the constructor), 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;
}