javascript 继承实现方式

面向对象与基于对象

几乎每个开发人员都有面向对象语言(比如C++、C#、Java)的开发经验。 在传统面向对象的语言中,有两个非常重要的概念 - 类和实例。 类定义了一类事物公共的行为和方法;而实例则是类的一个具体实现。 我们还知道,面向对象编程有三个重要的概念 - 封装、继承和多态。

但是在JavaScript的世界中,所有的这一切特性似乎都不存在。 因为JavaScript本身不是面向对象的语言,而是基于对象的语言。 这里面就有一些有趣的特性,比如JavaScript中所有事物都是对象, 包括字符串、数组、日期、数字,甚至是函数,比如下面这个例子:

var doc; //定义了一个doc基类
doc=(function(){
var _d;
 function doc(){
	this._d=window.document;
}
	doc.prototype.echo=function(){
		this._d.write("hell world");
		return 1;
	} //定义了一个属性echo
	return doc;
})();
使用:

var mydoc=new doc();
mydoc.echo(); //在页面显示hell world

模拟JavaScript中类和继承

/*
* 作者:杨贤喜
* 开发时间:2012-10-18
* 联系方式:120715852@qq.com
*/
//原自typescript 思路
var __extends = this.__extends || function(a,b){
	function __(){ this.constructor=a;}
	__.prototype=b.prototype;
	a.prototype=new __();
}

这就需要引入另外一个概念 - 原型(prototype),我们可以简单的把prototype看做是一个模版,新创建的自定义对象都是这个模版(prototype)的一个拷贝 (实际上不是拷贝而是链接,只不过这种链接是不可见,给人们的感觉好像是拷贝)。


实现类的继承

//DocMulit 继承doc
var DocMulit=(function(_doc){
	__extends(DocMulit,_doc);
	var txt,but;
	function DocMulit(){
		_doc.call(this);
		txt= this._d.createElement("input");
		but=this._d.createElement("button");
		but.innerText="单击这里";
		but.οnclick=function(){
		if(txt.value=='') {
		txt.focus(); //console.log(txt);
		}else{
			var doc_p=new DocP(txt.value);
			doc_p.echo();
		}	
		}
	}
//重写父类的 echo 的方法
	DocMulit.prototype.echo=function(){
		_doc.prototype.echo.call(this);//调用父类的echo方法
		this._d.body.appendChild(txt);
		this._d.body.appendChild(but);
	}
	return DocMulit;
})(doc);
//DocP 继承doc
var DocP=(function(_doc){
	__extends(DocP,_doc);
	var p_tar;
	function DocP(tar){
		_doc.call(this);
		this._d=window.document;
		this.p_tar=this._d.createElement("p");
		this.p_tar.innerText=tar;
		this.p_tar.setAttribute("title","Click here of delete");
		this.p_tar.setAttribute("style","cursor:pointer;");
		this.p_tar.οnclick=function(){
			if(confirm('You are delete?')){
				window.document.body.removeChild(this);
			}
		}
	}
//重写父类的echo方法
	DocP.prototype.echo=function(){
		this._d.body.appendChild(this.p_tar);
	}
	return DocP;
})(doc);
//实例化doc继承类DocMulit
var mydoc=new DocMulit();
mydoc.echo();

在页面上看到的效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值