三、还有一种简单实现
实现思路很简单,就是利用ECMAScript 5 原型式继承Object.create方法,封装成一个方法,如果不支持ECMAScript5的环境,就平移退化到
function F() {}; F.prototype = superCtor.prototype; ctor.prototype = new F(); ctor.prototype.constructor = ctor;
同样的,除最后一个参数是当前类的方法声明,其它参数均做为继承父类,需要循环继承,但当这里处理的相对比较简单,没涉及到覆盖。你可以自己动手添加。
var Class = (function() { /** * Inherits function.(node.js) * * @param ctor subclass's constructor. * @param superctor superclass's constructor. */ var inherits = function(ctor, superCtor) { // 显式的指定父类 ctor.super_ = superCtor; // ECMAScript 5 原型式继承并解除引用 if (Object.create) { ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } else { // 无Object.create方法的平稳退化 function F() {}; F.prototype = superCtor.prototype; ctor.prototype = new F(); ctor.prototype.constructor = ctor; } }; /** * Class function. */ return function() { // 最后一个参数是新类方法、属性和构造函数声明 var subClazz = arguments[arguments.length - 1] || function() {}; // initialize是构造函数,否构造函数就是一个空函数 var fn = subClazz.initialize == null ? function() {} : subClazz.initialize; // 继承除最一个参数以的类,多继承,也可以用作扩展方法 for (var index = 0; index < arguments.length - 1; index++) { inherits(fn, arguments[index]); } // 实现新类的方法 for (var prop in subClazz) { if (prop == "initialize") { continue; } fn.prototype[prop] = subClazz[prop]; } return fn; } })();
看下面实例:
/** * The definition of Cat Class. */ var Cat = Class({ /** * Constructor. * * @param name Cat's name */ initialize: function(name) { this.name = name; }, /** * Eat function. */ eat: function() { alert(this.name + " is eating fish."); } }); /** * The definition of Black Cat Class. */ var BlackCat = Class(Cat, { /** * Constructor. * * @param name Cat's name. * @param age Cat's age. */ initialize: function(name, age) { // call the constructor of super class. BlackCat.super_.call(this, name); this.age = age; }, /** * Eat function. */ eat: function() { alert(this.name + "(" + this.age + ") is eating dog."); } }); /** * The definition of Black Fat Cat Class. */ var BlackFatCat = Class(BlackCat, { /** * Constructor. * * @param name Cat's name. * @param age Cat's age. * @param weight Cat's weight. */ initialize: function(name, age, weight) { // call the constructor of super class. BlackFatCat.super_.call(this, name, age); this.weight = weight; }, /** * Eat function. */ eat: function() { alert(this.name + "(" + this.age + ") is eating dog. My weight: " + this.weight); } }); /** * The definition of Dog Class. */ var Dog = Class({}); var cat = new BlackFatCat("John", 24, "100kg"); cat.eat(); // true alert(cat instanceof Cat); // true alert(cat instanceof BlackCat); // true alert(cat instanceof BlackFatCat); // true alert(cat.constructor === BlackFatCat); // false alert(cat instanceof Dog);
本文导航
- 第1页: 首页
- 第2页: KLASS
- 第3页: 简单实现
- 第4页: mootools类库的Class