导航

  1. 常用CHM
  2. 订阅
  • 本站大部分内容从网上收集,收集目的仅供研究、学习。涉及版权或不希望收录您的文章请您及时与我联系。
  • 本站IM群,请自行选择。请各位朋友按照自己喜好加入。加入群后请及时发言,防止被清理。谢谢您的合作!!!
  • QQ群:Y①WEB开发(ASP.NET)号码:7351660 QQ群:Y②WEB开发(ASP+.NET)号码:11864905
  • QQ群:Y③WEB开发(DIV+CSS)号码:16610506 QQ群:Y④WEB开发(JS+AJAX)号码:16143998
  • QQ群:Y⑤WEB开发(新手)号码:12777715 MSN群:yaosansi[at]126.com
« JavaScript中基于类的继承使用XMLHttpRequest对象 »

Javascript综合使用

分类: JavaScript 发布: yaosansi 浏览: 日期: 2006年2月22日

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";
}
}
需要注意,SportsCar和CementTruck对象没有定义自己的wheelCount和curbWeightInPounds属性,也没有相关的存取函数,因为这些属性和函数会从Vehicle对象继承。
与前面一样,需要一个简单的HTML页面来测试这些新对象。代码清单5-6列出了测试这些新对象的HTML页面。要特别注意createInheritance函数,看看如何使用这个函数在Vehicle和SportsCar对象之间以及Vehicle和CementTruck对象之间创建继承关系。还要注意describe函数有所修改,试图直接访问wheelCount和curbWeightInPounds属性。这样做会返回一个undefined值。
代码清单5-6 classicalInheritance.html
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


Classical Inheritance in JavaScript




Examples of Classical Inheritance in JavaScript
















分别点击页面上的各个按钮会得到图5-17所示的结果。正如所料,试图直接访问私有属性就会返回undefined。

相关文章:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-Blog 1.8 Walle Build 100427

Copyright 2005-2010 yaosansi'site All Rights Reserved.
感谢系统大玩家为本站提供FTP空间
辽ICP备05021434号