转自:http://www.cnblogs.com/snandy/archive/2011/03/06/1972264.html
续上篇,
构造函数+原型 组装一个类;同一构造函数可以定义出多个类型
01 |
/** |
02 |
* $class 写类工具函数之二
|
03 |
* @param {Function} constructor
|
04 |
* @param {Object} prototype
|
05 |
*/
|
06 |
function $class(constructor,prototype) {
|
07 |
var c = constructor || function(){};
|
08 |
var p = prototype || {};
|
09 |
return function() {
|
10 |
for(var atr in p) {
|
11 |
arguments.callee.prototype[atr] = p[atr];
|
12 |
}
|
13 |
c.apply(this,arguments);
|
14 |
}
|
15 |
} |
与上一篇方式类似,仍然用构造函数,原型对象,定义两个类。
01 |
//构造函数 |
02 |
function Person(name) {
|
03 |
this.name = name;
|
04 |
} |
05 |
//原型对象 |
06 |
var proto = {
|
07 |
getName : function(){return this.name},
|
08 |
setName : function(name){this.name = name;}
|
09 |
} |
10 |
//写两个类 |
11 |
var Man = $class(Person,proto);
|
12 |
var Woman = $class(Person,proto);
|
与上一篇不同的是,虽然Man和Woman都是用Person,proto组装的。但Man却不等于Woman。即同一个构造函数(Person)可以定义出不同的类。
1 |
// 同一个构造函数(Person)定义不同的类 |
2 |
console.log(Man == Woman); //false
|