作为私有命名空间的函数

一、返回单个类的API

例如:

var set = (function invocation(){

      function Set(){  //构造函数的命名首字母需要大写

         this.values = {};

        this.n = 0;

      }


//给Set定义实例方法

Set.prototype.size = function(){

   return this.n;

}

return Set;  //返回这个构造函数。此处将Set()作为了一个公共的API给其他调用者使用

}());  //函数自我调用

如果想让代码在一个私有命名空间中运行,只需要给这段代码加上前缀“function(){”和后缀“}())”。

开始的左圆括号确保这是一个函数表达式,而不是函数定义语句,因此可以给该前缀添加一个函数名来让大妈变得更加清晰。


二、返回集合API,有3种方式。

1、直接返回一个对象,比如:

var collections;

if(!collections) collections = {};

collections.sets = (function namespace(){

   return {

      AbstractSet: AbstractSet,

      ArraySet: ArraySet

   };

}());


2、将模块函数单做构造函数,通过new来调用,并将它们赋值给this来将其导出

var collections;

if(!collections) collections = {};

collections.sets = ( new function namespace(){

    this.AbstractSet = AbstractSet;

   this.ArraySet = ArraySet;

}());


3、如果已经定义了全局命名空间对象,这个模块函数就可以直接设置那个对象的属性,不用返回任何内容。

var collections;

if(!collections) collections = {};

collections.sets = {};

(function namespace(){

   collections.sets.AbstractSet = AbstractSet;

   collections.sets.ArraySet = ArraySet;

});


猜你喜欢

转载自blog.csdn.net/zhouyy919/article/details/74837866
今日推荐