当我们要加的功能越来越多时,就会发现程序会越写越大,这样我们就需要更好的组织我们的程序,用类是最好方法,但FMS用的是AS1.0的语法,没有真正意义的类,但也能完成类的简
单功能,不管怎么样,总比没有类好,今天我们就来看一下如果在AS1.0里使用类,当然这不是真正的类.
现在我们将上一节中用到的用户列表做一下修改,写成一个类,上一节中我们用了userListArray这样一个数组来存储用户列表,现在我们把用户列表写成一个类:
先建一个UserList.asc文件,这就是我们要用的类的文件名,当然UserList也是类名(其实并不需要文件名和类名相同,因为这不是真正意义上的类)
- function UserList(){
- this.listArray = [];//也可以用new Array(),不过听说[]效率更高;
- }
-
- UserList.prototype.addUser = function(userName){
- this.listArray.push(userName);
- }
-
- UserList.prototype.delUser = function(userName){
- var len = this.listArray.length;
- for(var i=0;i<len;i++){
- if(this.listArray[i] == userName){
- this.listArray.splice(i,1);
- break;
- }
- }
- }
-
- UserList.prototype.checkOnline = function(userName){
- var len = this.listArray.length;
- for(var i=0;i<len;i++){
- if(this.listArray[i] == userName){
- return true;
- }
- }
- return false;
- }
-
- UserList.prototype.getUserList = function(){
- return this.listArray;
- }
function function UserList(){} 这个相当于类里面的构造函数
UserList.prototype. 这种相当于给UserList这个类加入方法,用过as1.0或者as2.0的朋友应该都知道prototype的用法
在这里我们加了四个方法
addUser 将用户加入到列表中
delUser 将用户从列表中删除
checkOnline 检查用户是否在列表中
getUserList 得到用户列表数组
这些代码应该很容易懂
再来看修改后的main.asc:
- load("UserList.asc");
- application.onAppStart = function() {
- this.chatMsgArray = new Array();
- this.userList = new UserList();
- }
-
- application.onConnect = function(client, userName) {
- if(this.userList.checkOnline(userName)){
- this.rejectConnection(client);
- return;
- }
- this.acceptConnection(client);
- client.userName = userName;
- this.userList.addUser(userName);
- sendUserList();
- //客户端调用方法
- client.getMsg = function(){
- return application.chatMsgArray;
- }
- client.sendMsg = function(msg){
- var chatInfo = this.userName + " : " + msg;
- application.chatMsgArray.push(chatInfo);
- sendMsgToClient(chatInfo);
- }
- }
-
- application.onDisconnect = function(client) {
- trace("用户:"+client.userName+" 离开");
- this.userList.delUser(client.userName);
- sendUserList();
- }
-
-
- application.onAppStop = function() {
-
- }
-
- function sendMsgToClient(chatInfo){
- var len = application.clients.length;
- for(var i=0;i<len;i++){
- application.clients[i].call("getMsgInfo",null,chatInfo);
- }
- }
-
- function sendUserList(){
- var len = application.clients.length;
- for(var i=0;i<len;i++){
- application.clients[i].call("getUserList",null,application.userList.getUserList());
- }
- }
跟上一节的代码相比,首先多了一个load(”UserList.asc”),load能够将其它的asc文件加入进来,相当于导入了,也可以理解为包括,就是两个文件成了一个文件
其他的修改应该很简单,很容易看懂,我就不多讲了.
从这个程序代码的多少上看,并没有减少多少,但这只是一个小程序,当程序越大时就能看出这样写的好处了.
客户端不用改,现在看一下效果,应该和上一节是一样的.
下节继续.
(本教程如需转载请注明出处!)