当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript学习笔记:创建对象和构造类

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 JavaScript学习笔记:创建对象和构造类


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 430 ::
收藏到网摘: n/a

创建一个对象
Java代码
 <script type="text/javaScript"> var newObject=new Object(); //创建一个对象 newObject.firstName="frank"; //增加一个firstName属性 newObject.sayName=function(){ alert(this.firstName); } //添加一个sayName方法
//调用sayName方法
// newObject.sayName();
// newObject["sayName"](); var FirstName=newObject["firstName"]; var whatFunction;
// if(whatVolume==1){
// whatFunction="sayName";
// }else if(whatVolume==2){
// whatFunction="sayLoudly"
// }
// newObject[whatFunction](); function sayLoudly(){ alert(this.firstName.toUpperCase()); } newObject.sayLoudly=sayLoudly; //另一种方式添加方法 newObject["sayLoudly"](); </script>

利用json(javaScript Object Notation)创建对象和上面同样的效果。
Java代码
 function sayLoudly(){ alert(this.firstName.toUpperCase()); } var newObject={ firstName:"frank", sayName:function(){alert(this.firstName);}, sayLoudly:sayLoudly };
//也可以这样 var newObject={ firstName:"frank", sayName:function(){alert(this.firstName);}, sayLoudly:sayLoudly, lastName:{ lastName:"ziggy", sayName:function(){alert(this.lastName);} } }; newObject.lastName.sayName();

这样也ok
Java代码
 function sayLoudly(){ alert(this.name.toUpperCase()); } function sayName(){ alert(this.name); } var newObject={ name:"frank", sayName:sayName, sayLoudly:sayLoudly, lastName:{ name:"ziggy", sayName:sayName } }; newObject.lastName.sayName();

JavaScript 中的类,还有构造方法。。。
Java代码
 function newClass(){ alert("constructor"); this.firstName="frank"; this.sayName=function(){alert(this.firstName);} // return this; } //var nc=newClass(); var nc=new newClass(); //nc.firstName="ziggy"; is ok nc.sayName();

还可以这样来构造类
Java代码
 function newClass(){ this.firstName="frank"; } newClass.prototype.sayName=function(){ alert(this.firstName); } var nc=new newClass(); nc.firstName="ziggy"; nc.sayName(); var nc2=new newClass(); nc2.sayName();

一般用prototypes来添加方法,这样不管有多少个实例,在内存中只有一个sayName方法。