Transferred from:Http://www.cnblogs.com/snandy/archive/2011/03/06/1972254.html
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
02 |
* $ Class write tool function |
03 |
* @param {Function} constructor |
04 |
* @param {Object} prototype |
06 |
function $class(constructor,prototype) { |
07 |
var c = constructor || function(){}; |
08 |
var p = prototype || {}; |
The constructor is used to generate the attributes (fields) of the class instance. The prototype object is used to generate the class instance method.
02 |
function Person(name) { |
07 |
getName : function(){return this.name}, |
08 |
setName : function(name){this.name = name;} |
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:
1 |
console.log(Man == Woman); //true |
2 |
console.log(Man.prototype == Woman.prototype); //true |
Create an object
1 |
var man = new Man("Andy"); |
2 |
var woman = new Woman("Lily"); |
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.
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:
1 |
function $class(constructor,prototype) { |
2 |
var c = constructor || function(){}; |
3 |
var p = prototype || {}; |
6 |
c.prototype[atr] = p[atr]; |