如何用面向对象的思想来写javascript,对于初学者应该是比较难的,我们经常用的jquery其实也是用面向对象的思想去封装的,今天我们来看看如何在javascript中用interface,在c#还是java中都应该面向接口设计我们的程序,在c#和java中都interface这样的关键字,但是javascript中没有相应的机制,但是javascript很灵活,我们可以用它的特性去模仿interface,但是我们需要加入一些methods来做check的动作。
我们来看下一个interface的作用:
继承了这个Interface就必须要实现这个Interface中定义的方法(方法签名)
//JavaScript 现在还做不到方法的签名的约束
var Interface = function (name, methods) {
if (arguments.length != 2) {
throw new Error("the interface length is bigger than 2");
立即学习“Java免费学习笔记(深入)”;
}
this.Name = name;
this.Method = [];
for (var i = 0; i
if(typeof methods[i]!== string) {
throw new Error("the method name is not string");
} this.Method.push(methods[i]);
}
}
/*static method in interface*/
Interface.ensureImplement = function (object) {
if (arguments.length
技术上面应用了三层结构,AJAX框架,URL重写等基础的开发。并用了动软的代码生成器及数据访问类,加进了一些自己用到的小功能,算是整理了一些自己的操作类。系统设计上面说不出用什么模式,大体设计是后台分两级分类,设置好一级之后,再设置二级并选择栏目类型,如内容,列表,上传文件,新窗口等。这样就可以生成无限多个二级分类,也就是网站栏目。对于扩展性来说,如果有新的需求可以直接加一个栏目类型并新加功能操作
throw new Error("there is not Interface or the instance");
}
for (var i = 1; i
var interface1 = arguments[i];
if (interface1.constructor !== Interface) {
throw new Error("the argument is not interface");
}
for (var j = 0; j
var method = interface1.Method[j];
if (!object[method] || typeof object[method] !== function) {
throw new Error("you instance doesnt implement the interface");
}
}
}
}
我们来分析一下code,我们现在的做法是用来比较一个Instance中的方法名在接口中是否定义了。
我先定义一个接口(2个参数),第二个参数是接口中的方法名。Check方法用简单的2层for循环来做比较动作。
我们来看下如何去用这个接口:
var Person = new Interface("Person", ["GetName", "GetAge"]); var Man = function (name, age) { this.Name = name; this.Age = age; } Man.prototype = { GetName: function () { return this.Name; }, // GetAge: function () { return this.Age; } } var test = function (instance) { Interface.ensureImplement(instance, Person); var name = instance.GetName(); alert(name); } test(new Man("Alan",20));
如果我们注释了上面的GetAge方法,在执行的时候就会出错。在ensureImplement的时候发现并没有去实现这个方法。










