首页 > 语言 > JavaScript > 正文

实现JavaScript中继承的三种方式

2024-05-06 14:13:29
字体:
来源:转载
供稿:网友
一、原型链继承
  在原型链继承方面,JavaScript与java、c#等语言类似,仅允许单父类继承。prototype继承的基本方式如下:
代码如下:
function Parent(){}
function Child(){}
Child.prototype = new Parent();

  通过对象Child的prototype属性指向父对象Parent的实例,使Child对象实例能通过原型链访问到父对象构造所定义的属性、方法等。
  构造通过原型链链接了父级对象,是否就意味着完成了对象的继承了呢?答案是否定的。如:
代码如下:
function Parent(){}
function Child(){}
Child.prototype = new Parent();
var child = new Child();
alert(child.constructor);//function Parent(){}
alert(child instanceof Child);//true

  尽管child依然可以作为Child的实例使用,但此时已经丢失了实例child原有的对象构造信息。弥补该缺陷的方法如下:
代码如下:
function Parent(){}
function Child(){}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child();
alert(child.constructor);//function Parent(){}
alert(child instanceof Child);//true

  如上代码片段“Child.prototype.constructor = Child”所示,通过显示地指定对象构造Child的原型,强制所有的Child对象实例的构造都为Child。
二、使用apply、call方法
  由于JavaScript内置的Function对象的apply、call方法改变对象构造中“this”的上下文环境,使特定的对象实例具有对象构造中所定义的属性、方法。
  使用apply、call继承,在实际开发中操作HTML页面上的DOM对象时尤为常用。如:
代码如下:
  <div id="extend">apply,call继承</div>
  <script language="javascript">
  function ext()
  {
     this.onclick=function(){alert(this.innerHTML)}
  }
  ext.apply(document.getElementById("extend"));
  ext.call(document.getElementById("extend"));
  </script>

  通过apply或call定义的ext方法,使ext方法内部的this上下文表示为DOM对象“<div id="extend">apply,call继承</div>”。
  值得注意的是,当使用apply、call时,会直接执行对象构造所定义的代码段,如:
代码如下:
  <script language="javascript">
  function testExec()
  {
     alert("执行!");
  }
  testExec.call(null);//弹出execute对话框
  testExec.apply(null);//弹出execute对话框
  </script>

三、对象实例间的继承
  JavaScript对象的多态性,允许实例动态地添加属性、方法。该特性造就了JavaScript中的另一种继承手法——对象实例间的继承。如:
代码如下:
  var Person = {name:"nathena",age:"26"};
  var nathena = {sex:"male"};
  (function inlineExtends(so,po)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选