知识大全 Javascript 继承实现方式

Posted 语言

篇首语:知识贵在质,不在量。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 Javascript 继承实现方式相关的知识,希望对你有一定的参考价值。

Javascript 继承实现方式  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!

  面向对象与基于对象

  几乎每个开发人员都有面向对象语言(比如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 ;

   //定义了一个属性echo

  return doc;

  )()

  使用

  var mydoc=new doc()

  mydoc echo() //在页面显示hell world

  模拟JavaScript中类和继承

  /*

  * 作者 杨贤喜

  * 开发时间

  * 联系方式

  */

  //原自typescript 思路

  var __extends = this __extends || function(a b)

  function __() nstructor=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 onclick=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 onclick=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()

  在页面上看到的效果

cha138/Article/program/Java/JSP/201311/19220

相关参考