如何设计兼容移动端调用的API?

定义了一个widget用于显示在页面上,使用JS object实现,
但是根据用户客户端是否是mobile有不同的处理方式。
如何更好的组织代码,让调用更加方便?
希望调用方式是统一的,不需要判断是否为移动端。

方案一:
mywidget = new com.xxx.widget(...);

com.xxx.widget = {
//在这里区分移动端PC端,如何写代码
}

方案二:

mywidget = (//如何写调用代码...);

//移动端PC端分别实现
com.xxx.widget_pc = {

}
com.xxx.widget_mobile = {

}

阅读 4.3k
2 个回答

使用类的继承覆盖机制,是比较好的选择。

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后缀的方法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题