跟我一塊兒動手寫js庫--JavaScript之繼承與多態

繼承的話我這裏主要是傳統的原型繼承方式。關於原型繼承,這個在網上已經有現有的輪子了(參考了慕課網Bosn老師的JavaScript深刻淺出一篇的原型繼承的視頻講解),我就站在巨人的肩上給稍微改動了下了app

Object.prototype.extends = function(SuperClass) {
	
	if(!Object.create) {
		Object.create = function(proto) {
			function F() {
				
				F.prototype = proto;
				return new F;
			}
		}
	}
	var oldPrototype = this.prototype;
	this.prototype = Object.create(SuperClass.prototype);
	
//	this.prototype.constructor = SuperClass;
	for(key in oldPrototype) {
		oldPrototype[key] !=undefined && (this.prototype[key]=oldPrototype[key]);
	}
	this.prototype.__parent__ = SuperClass;
};
Object.prototype.super = function() {
	
	var param = arguments[0];
	var arg = arguments;
	
	while(param) {
		
		if(!param.callee) {
			break;
		}
		arg = param;
		param = param[0];
	}

	var parent = this;
	
	while(parent) {
		
		for(var key in parent) {//首次子類調用該方法
			
			if(arguments[0].callee == parent[key]) {//找到對應父類
				arg.callee = arguments[0].callee;
				parent.__parent__.prototype[key].apply(this, arg);
				return;
			}
		}
		for(var key in parent.prototype) {
			
			if(arguments[0].callee == parent.prototype[key]) {//找到對應父類
				arg.callee = arguments[0].callee;
				parent.prototype.__parent__.prototype[key].apply(this, arg);
				return;
			}
		}
		parent = parent.__parent__;
	}
};

Object.defineProperties(Object.prototype, {
	'extends': {
		enumerable: false,
		writable: false
	},
	'super': {
		enumerable: false,
		writable: false
	}
});

使用例子:this

var Person = function() {};

Person.prototype = {
    say: function() {
        console.log("person say");
    }
};

var Father = function() {};

Father.prototype = {
    say: function() {
        this.super(arguments);
        console.log("father say");
    }
}

Father.extends(Person);

var Son = function() {};

Son.prototype = {
    say: function() {
        this.super(arguments);
        console.log("son say");
    }
}

Son.extends(Father);

var son = new Son();
son.say();

var Daughter = function() {};

Daughter.prototype = {
    say: function() {
        this.super(arguments);
        console.log("daughter say");
    }
}

Daughter.extends(Father);

var daughter= new Daughter();
daughter.say();

/************* 打印結果 ***************/.net

person say
father say
son say
person say
father say
daughter say

多態主要是在方法裏面經過調用this.super(arguments)就會自動向上調用父類的同名方法。以上即是本次的js代碼庫分享,但願你們多多指點、多多評論,也但願我之後能給你們帶來更多有用的庫方法或者類。歡迎轉載,原文出處 http://www.javashuo.com/article/p-adskjsfx-dw.htmlprototype

相關文章
相關標籤/搜索