popmenu2.01发布和JavaScript代码的封装

popmenu2.01的效果演示如下:
http://www.oceanstudio.net/oceanstudy/learn/js/popmenu2.01/example.htm
popmenu2.01的功能并不太强大,但是封装的结构非常好。一般而言,封装可以采用htc,也可以直接用js。怎么样来直接用js呢?在js里面实际上也有对象的概念。function有一种特殊的用法。就是相当于C#的class,可以定义一个类。比如popmenu中是这样定义的。
function popMenu(menuName,called,menuItem) {
           this.menuName = menuName; //菜单名
           this.called = called;  //呼叫函数
           this.menu = null;   //菜单的指针
           this.menuItem = new Array(); //菜单项
           if (menuItem != null)
                      this.menuItem = menuItem;
                     this.parentObj = null;   //所依赖的对象
                    //样式属性  
                     this.backgroundColor = "#f1f1f1";
             ..................
}
在使用的时候怎么用呢?直接new就可以了。
var pop = new popMenu(...);
这样是不是很像一个类呢?
那么这个类的方法怎么写呢?这个需要用到prototype属性,比如要增加一个setItem方法,如下:
//设置菜单项
popMenu.prototype.setItem = function (menuItem) {
       if (menuItem != null)
                this.menuItem = menuItem;
 
               var html = "";
               for (var i = 0;i<this.menuItem.length;i++) {
                html += '<div onclick="' + this.menuName + '.doClick(this)" onmouseover="' + this.menuName + '.doMouseOver(this)"                      onmouseout="' + this.menuName + '.doMouseOut(this)" style="border:1px solid                             '+this.backgroundColor+';height:'+this.height+';padding:3px">';
                html += this.menuItem[i] + "</div>";
        }
        this.menu.innerHTML = html;
}
调用的时候就直接:
var pop = new popMenu(...);
pop.setItem(...);
嘿嘿,大家看看这个例子就可以知道里面的奥妙。这个popmenu写了应该有2年多时间了。以前在dev-club公布过popmenu1.0的源码。但是1.0中有一个显著bug导致实用性不太好。这次公布的时popmenu2.01源码。
还有更多精彩可以到
http://sps.oceanstudio.net
下载

posted on 2004-12-11 13:42  ocean  阅读(831)  评论(1编辑  收藏  举报

导航