最近心血来潮,想开发一个基于Google Map的留言本,磨炼一下自己的Js水平。
首先,需要一个Div在页面中显示当前信息,例如正在装载,正在提交留言以及返回操作是否成功等。如果直接用alert()给出就算不得是User Friendly了。其实一个函数就能搞定,不过为了学点javascript类方面的知识,还是自己给自己找点麻烦好了——这句话其实不对,因为javascript里函数本身就是对象。闲话不说了,先把这个类贴出来
 1//---------------------------------------------------------------------------
 2//                                    GMapbookInfo类
 3//---------------------------------------------------------------------------
 4var Class = {
 5  create: function() {
 6    return function() {
 7      this.initialize.apply(this, arguments);
 8    }

 9  }

10}

11var GMapbookInfo = Class.create();
12GMapbookInfo.prototype = {
13    initialize: function(container) {
14        var parent = container.parentNode;
15        // Make the wrapper div.
16        var wrapper = document.createElement("div");
17        wrapper.style.cssText = container.style.cssText;
18        parent.insertBefore( wrapper, container );
19        
20        // Move the container into the wrapper.
21        parent.removeChild(container);
22        wrapper.appendChild(container);
23        container.style.cssText = "position: relative; width: 100%; height: 100%;";
24        
25        this.backgroundColor = "#9999cc";
26        this.borderColor = "#666699";
27        
28        // Add the overlay div.
29        this.overlay = document.createElement("div");
30        wrapper.appendChild(this.overlay);
31        this.visibleStyle = "position: relative; top: -55%; background-color: " + this.backgroundColor + "; width: 40%; text-align: center; margin-left: auto; margin-right: auto; padding: 2em; border: 0.08in ridge "+ this.borderColor + "; z-index: 100; opacity: .75; filter: alpha(opacity=75);";
32        this.invisibleStyle = "display: none;";
33        this.overlay.style.cssText = this.invisibleStyle;
34    }
,
35    show : function (message) {
36        this.overlay.innerHTML = message;
37        this.overlay.style.cssText = this.visibleStyle;
38    }
,
39    hide : function (){
40        this.overlay.style.cssText = this.invisibleStyle;
41    }
,
42    setBackgroundColor : function (color) {
43        this.backgroundColor = color;
44    }
,
45    setBorderColor  : function (color) {
46        this.borderColor = color;
47    }

48}

49

首先是下面这段代码,前7行是从prototype里拷贝出来的,因为喜欢var NewObject= Class.create()这种类的创建方式
这段代码的意思是类名为Class的对象中有个create方法,该方法创建一个新对象(即return function(){...},记住JS的类基于prototype,函数即对象),并把该对象通过new传递过来的参数赋值给新类的构造函数initialize(即this.initialize.apply(this, arguments))。
1var Class = {
2  create: function() {
3    return function() {
4      this.initialize.apply(this, arguments);
5    }

6  }

7}

8var GMapbookInfo = Class.create();

 后面代码{...}里的内容就是一个新的类,再把该类传递给GMapbookInfo的prototype,这样就完成了JS类的创建
当然,创建类也有别的办法,如下
首先定义类,有两种方法
function newObj(arg) { this.arg = arg } 或 var newObj= function() {...}
定义类属性或方法可如下定义
newObj.prototype.propertyA = xxx;
newObj.prototype.methodA = function(){...};

posted on 2006-11-22 22:08  kukukuan  阅读(751)  评论(0编辑  收藏  举报