Ajax基础教程(5)- 5.7 实现高级JavaScript技术

http://tech.ddvip.com   2007年11月21日    社区交流

本文详细介绍Ajax基础教程(5)- 5.7 实现高级JavaScript技术

  createInheritance函数有两个参数,父对象和子对象。这个函数只是迭代处理父对象的所有成员(成员就是属性或函数),如果某个成员在子对象中不存在,则复制到子对象。

  使用createInheritance函数相当简单:首先创建子对象的一个实例,然后使用createInheritance函数,为它传递子对象以及父对象的一个实例,如下:

  var child = new Child();
  createInheritance(new Parent(), child);

  父对象中有而子对象中没有的所有属性和方法将复制到子对象。

  5.7.4 汇合

  前面已经了解到,JavaScript中也可以实现私有属性,而且JavaScript也能像C++和Java一样支持基于类的继承方法。为了展示这些是怎样实现的,下面说明如何转换前面使用Vehicle、SportsCar和CementTruck对象的示例,从而使用信息隐藏和继承的新模式。代码清单5-5列出了新的对象定义。

  代码清单5-5 classicalInheritance.js

  function Vehicle() {
  var wheelCount = 4;
  var curbWeightInPounds = 4000;
  this.getWheelCount = function() {
  return wheelCount;
  }
  this.setWheelCount = function(count) {
  wheelCount = count;
  }
  this.getCurbWeightInPounds = function() {
  return curbWeightInPounds;
  }
  this.setCurbWeightInPounds = function(weight) {
  curbWeightInPounds = weight;
  }
  this.refuel = function() {
  return "Refueling Vehicle with regular 87 octane gasoline";
  }
  this.mainTasks = function() {
  return "Driving to work, school, and the grocery store";
  }
  }
  function SportsCar() {
  this.refuel = function() {
  return "Refueling SportsCar with premium 94 octane gasoline";
  }
  this.mainTasks = function() {
  return "Spirited driving, looking good, driving to the beach";
  }
  }
  function CementTruck() {
  this.refuel = function() {
  return "Refueling CementTruck with diesel fuel";
  }
  this.mainTasks = function() {
  return "Arrive at construction site, extend boom, deliver cement";
  }
  }

来源:CSDN    责编:豆豆技术应用

正在加载评论...