当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript 创建对象和构造类实现代码

Javascript
Add a Table to a Word Document
Add Formatted Text to a Word Document
用jscript实现新建word文档
用jscript实现新建和保存一个word文档
Open and Print a Word Document
Use Word to Search for Files
Convert Seconds To Hours
Sample script that deletes a SQL Server database
Sample script that displays all of the users in a given SQL Server DB
firefox中用javascript实现鼠标位置的定位
div+css实现鼠标放上去,背景跟图片都会变化。
Locate a File Using a File Open Dialog Box
Save a File Using a File Save Dialog Box
用jscript实现列出安装的软件列表
List the Stored Procedures in a SQL Server database
Display SQL Server Login Mode
Display SQL Server Version Information
List all the Databases on a SQL Server
用jscript启动sqlserver
Stop SQL Server

Javascript 中的 JavaScript 创建对象和构造类实现代码


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

JavaScript学习笔记:创建对象和构造类. 创建一个对象
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方法。