自创js类与继承的实现

研究了一下js的面向对象编程,模拟了一下类定义和继承,尝试过用原型来做,但是总是做不了,后来用了别的方法,可能不是最好的方法,有见解的同学欢迎评论。

function dump(o){
	console.log(o);
}
//模拟类和继承
function Class(args){
	a=function(){
		this.init=function(){
			alert('没有为类建立初始化函数');
		}
		//添加自定义参数
		for(var p in args){
			this[p]=args[p];
		}
		//初始化的时候执行
		this.init.apply(this,arguments);
	}
 
	a.extend=function(args){
		//添加自定义参数
		t=new this();//实例化一个父类,会执行父类的初始化函数
		for(var p in args){
			t[p]=args[p];
		}
		return Class(t);
	}
	return a;
}
//定义父类
var Parent=Class({
	p:1,
	//init为实例化时执行的初始化函数,雷同于php中的构造函数
	init:function(){
		this.p=4;
		alert(this.p);
	}
});
//定义子类1
var Son=Parent.extend({//继承Parent类
	s:2,
	init:function(str2){
		alert(this.s);
	}
});
//定义子类2
var Son2=Son.extend({
	s2:3,
	init:function(str3){
		alert(this.s);
	}
});
 
var p=new Parent('a');
dump(p);
var s=new Son('b');
dump(s);
var s2=new Son2('b3');
dump(s2);

输出的结果:

12 Responses to 自创js类与继承的实现 »

  1. 嘻跃相逢 评论 2010-10-20 23:53

    感谢,学习。

    回复

  2. ktmud 评论 2010-10-24 11:40

    这么想写js… 就… 来淘宝吧!

    回复

    Joe 回复 十月 25th, 2010 at 22:13

    回复

  3. 孙空空 评论 2010-10-24 23:39

    我也该学习学习了。

    回复

  4. juan 评论 2010-10-29 10:56

    我会写页面,页面写的还不错在公司里被公认是最好的,我不会写js但是很会修改别人的,只要有类似的效果我都能改成自己想要的,曾经也很努力的学过但是发现太难,后来就放弃了,现在我但心这样下去如果不学会不会被这个行业淘汰。

    回复

    joe 回复 十月 29th, 2010 at 21:59

    会,重构目前渐渐需要了解js了,html5说了算

    回复

  5. 第一先生 评论 2010-11-01 12:03

    学习一下吧,辛苦博主了

    回复

  6. 甜甜 评论 2010-11-07 10:12

    不错学习了

    回复

  7. reizhi 评论 2010-11-12 19:21

    好吧我看不懂,就只是来踩踩

    回复

  8. 小杨 评论 2010-12-17 16:37

    以前用c实现过继承, js没做过。。

    回复

  9. crossyou 评论 2011-02-09 15:49

    发现结果并不是我所想的。

    回复

  10. 『学习』Javascript类继承实现 一则 – CrossYou'Blog Pingback 2011-02-09 23:59

    [...] 不久前在写笔记的小JOE页的博客上看到一篇名为《自创js类与继承的实现》的文章,最近自己狠劲折腾js便想起了这篇文章,于是我结合着QQ地图里的代码,简单的也写了一个JS类继承的实现,代码如下: function extend(destination, source) { var value = null; var property = null; if (destination && source) { for (property in source) { value = source[property]; if (value !== undefined) { destination[property] = (typeof(value) == ‘object’ && !(value.nodeType) && !(value instanceof Array)) ? extend({}, value) : value; } } if (source.hasOwnProperty && source.hasOwnProperty(‘toString’)) { destination.toString = source.toString; } } return destination; } [...]

Leave a Reply

Email address is not published

You should say a Chinese word to pass spam check. If you can not input Chinese, just copy 你好 and paste them into comment text box.