日期:2014-05-16  浏览次数:20506 次

JS组合继承的通用工具函数

此工具函数没实际意义,只是鉴于EXT的extend方法不太好理解,写了一个简化的extend方法,帮助理解.

/**
 * 
 */
E = {};
E.extend = function(sub, sup) {
	//借用构造函数
	sub.prototype = sup;
	//保留父类的构造函数,以便在子类构造函数中用调用,将父类变量绑定在this下
	sub.prototype.superclass = sup.constructor;
	//因为重写了构造函数所以重新指定constructor,以使instanceof表现正常
	sub.prototype.constructor = sub;
	//因为已经将变量绑定到子类上,所以删除原型上被覆盖的变量
	for (var i in sup) {
		if (typeof sup[i] !== 'function') {
			delete sup[i];
		}
	}
	return sub;
};

E.InterfaceFactory = {};
E.InterfaceFactory.createInterface = function(methods) {
	var Interface = function() {};
	var f = typeof arguments[0] === 'string';
	var p = f ? arguments : arguments[0];
	var len = p.length;
	var _proto = Interface.prototype = {};
	for (var i = 0; i < len; i++) {
		_proto.p[i] = function() {
			throw new Error('no implements function');
		};
	}
	return new Interface();
};


Test

var Person = function(name) {
		this.name = name;
	}
	Person.prototype.say = function () {
		alert('I am ' + this.name);
	}
	
	var SS = function(name, age) {
		this.superclass.call(this,name);
		this.age = age;
	}
	
	SS = E.extend(SS, new Person('sz'));
	var s = new SS('xx', 11);
	s.say();