0
点赞
收藏
分享

微信扫一扫

当JS面向对象之后续(JS在设计级联菜单时)

我们在使用JS制作控件时,经常使用的方法就是建立一个function对象,然后对function的原型对象进行扩展对象的建立,这样在建立function对象的实例后,就可以访问到prototype原型所指定的新对象了.例如:

定义一个function对象

function zzl(){…}

为zzl对象建立一个原型扩展对象

zzl.prototype = {

 zzl.prototype = {
display: function () {
alert("欢迎您");
},
property: {
name: "zzlController",
version: "1.1.0",
Isregister: true
},
showinfo: function (version) {
alert("版本:" + version);
}

}
zzl = new zzl();
zzl.showinfo(zzl.property.version);

有了上面的概念基础之后,再看我们设计的菜单

代码结构:

​​

当JS面向对象之后续(JS在设计级联菜单时)_扩展方法

​​

源代码如下:

/ 菜单添加到容器中
var zzlMenuBlock = {
list: new Array(),
add: function(component) {
this.list.push(component);
},
print: function(container) {
var str = "<ul class=\"Menu\">";
for (var i = 0, len = this.list.length; i < len; i++) {
str += this.list[i].getValue();
}
document.getElementById(container).innerHTML = str + "</ul>";
}
}
// 主菜单,必须有子菜单的菜单项
function zzlMenu(text, title, href) {
this.menuComponents = new Array();
this.text = text;
this.title = title;
this.href = href;
}
// 主菜单的扩展方法
zzlMenu.prototype = {
getValue: function() {
if (this.menuComponents.length == 0) {
throw new Error(this.text + "菜单下没有子菜单");
}
var str = "<li class=\"Menu-WithChildren\" title=\"" + this.title + "\">
<a class=\"Menu-Link\" href=\"" + this.href + "\">" + this.text + "</a>";
str += "<ul>";
for (var i = 0, len = this.menuComponents.length; i < len; i++) {
str += this.menuComponents[i].getValue();
}
str += "</ul>";
return str;
},
add: function(component) {
this.menuComponents.push(component);
},
remove: function(component) {
for (var i = 0, len = this.menuComponents.length; i < len; i++) {
if (this.menuComponents[i] == component) {
this.menuComponents.splice(i, 1);
break;
}
}
},
removeAt: function(index) {
if (this.menuComponents.length <= index) {
this.menuComponents.splice(index, 1);
}
else {
throw new Error("索引操作数组超过上限");
}
}
}
// 子菜单,一定没有下级菜单
function zzlItem(text, title, href) {
this.text = text;
this.title = title;
this.href = href;
}
// 子菜单的扩展方法
zzlItem.prototype = {
getValue: function() {
var str = "<li class=\"Menu-Leaf\" title=\"" + this.title + "\">

<a href=\"" + this.href + "\">" + this.text + "</a></li>";

return str;
}


}

var zzlMenuBlock = {


作者:仓储大叔,张占岭,
荣誉:微软MVP

当JS面向对象之后续(JS在设计级联菜单时)_子菜单_02



举报

相关推荐

0 条评论