service 服务

service 用面向对象的方式将公用逻辑封装起来。

1.示例

// 定义服务
_n.service('user', {
  hasSignin: function(){
    return false;
  }
});
// 使用服务
var user = _n.service('user');
console.log(user.hasSignin());

service的值可以是任何类型,包括非true的值(false, undefined, null, 0)。

2.入口函数

service对象如果存在init方法,会被自动调用。

// 定义服务
_n.service('play', {
  isInit: false;
  init: function(){
    if(!this.isInit) {
      this.isInit = true;
      console.log('play service init');
    }
    return this;
  }
});
// 调用服务
var play = _n.service('play');

3.工厂模式

// 定义服务
_n.service('dateTime', (function() {
  var dateTime = function () {
    this.date = new Date()
    return this;
  }
  dateTime.prototype.show = function () {
    alert(this.date.toString());
  }
  return {
    dateTime: dateTime
    create: function() {
      return new this.dateTime()
    }
  }
}()));
// 调用服务
var dateTime = _n.service('dateTime').create();
dateTime.show();

*使用init作为入口可自动创建实例

4.单例模式

// 定义服务
_n.service('dateTime', (function() {
  var dateTime = function () {
    this.date = new Date()
    return this;
  }
  dateTime.prototype.show = function () {
    alert(this.date.toString());
  }
  return {
    dateTime: dateTime
    init: function() {
      if(!this.instance) {
        this.instance = new this.dateTime();
      }
      return this.instance;
    }
  }
}()));
// 调用服务
var dateTime = _n.service('dateTime');
dateTime.show();