定义了一个widget用于显示在页面上,使用JS object实现,
但是根据用户客户端是否是mobile有不同的处理方式。
如何更好的组织代码,让调用更加方便?
希望调用方式是统一的,不需要判断是否为移动端。
方案一:
mywidget = new com.xxx.widget(...);
com.xxx.widget = {
//在这里区分移动端PC端,如何写代码
}
方案二:
mywidget = (//如何写调用代码...);
//移动端PC端分别实现
com.xxx.widget_pc = {
}
com.xxx.widget_mobile = {
}
var Widget = function () {
if (手机端) {
this.device = 'mobile';
} else (PC端){
this.device = 'desktop';
}
}
Widget.prototype = {
constructor: Widget,
init: function (arguments) {
if (this.device === 'mobile') {
return init_mobile(arguments);
}
//do something on desktop...
},
init_mobile: function (arguments) {
//do something on mobile...
},
...
};
js
代码掺杂着伪代码,差不多就是在函数开头判断如果是mobile设备,则调用_mobile后缀
的方法。
使用类的继承覆盖机制,是比较好的选择。