Create Class:
var Class = function(parent){ var klass = function(){ this.init.apply(this, arguments); }; if(parent) { var subclass = function(){}; subclass.prototype = parent.prototype; klass.prototype = new subclass; } klass.prototype.init = function(){}; klass.fn = klass.prototype; klass.fn.parent = klass; klass.proxy = function(func){ var self = this; return (function(){ func.apply(self, arguments); }); }; klass.fn.proxy = klass.proxy; klass.extend = function(obj){ var extended = obj.extended; for(var i in obj){ klass[i] = obj[i]; } if (extended) extended(klass) }; klass.include = function(obj){ var included = obj.included; for(var i in obj){ klass.fn[i] = obj[i]; } if (included) included(klass) }; return klass; };
Demo:
var Person = new Class; Person.include({ init: function(name, age){ this.name = name; this.age = Person.checkAge(age) ? age : null; }, sayHello: function(){ console.log("Hi , My name is " + this.name + (this.age ? ", i am " + this.age + " years old this year" : "")); } }); Person.extend({ needWater: true, checkAge: function(age){ return age>0 && age < 150; } }); var jim = new Person("Jim", 10); jim.sayHello(); //output:Hi , My name is Jim, i am 10 years old this year var tom = new Person("Tom", -1); tom.sayHello(); //output:Hi , My name is Tom
extend中是静态属性和方法,include中是实例属性和方法。
当属性和方法与具体实例无关或是公用的时候,用静态属性和方法,否则用实例属性和方法。