最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What is this design pattern known as in JavaScript? - Stack Overflow

programmeradmin0浏览0评论

I was looking over the js source code for Scrabb.ly.

I've noticed that they would do something like so for each of their distinct "classes":

var Board = (function() {
  var self = {};

  // settings for board
  self.options = {
    debug: true,
    addedPlayTiles: function() {},
    clearedPlayTiles: function() {}
  };

  // set to true once the board has been setup
  self.isSetup = false;

  // quick access to square elements
  self.squares = {};
  self.squareCount = 0;

  self.setup = function(options) {
    self.log("Setting up board!");

    // set options
    _.each(options, function(val, key) {
      self.options[key] = val;
    });

    return self;
})();

Some code from the middle has been omitted but this should give you the general idea.

  1. What is the purpose of the the following: (function() { // code })(); Is this the module pattern that I've seen talked about? Is this meant to keep the global namespace clean?
  2. What does this line mean?: var self = {} Is the self object used to exposed 'public' members? How would you define a private function or variable?
  3. How would you instantiate multiple "Boards" if you wanted to?

I was looking over the js source code for Scrabb.ly.

I've noticed that they would do something like so for each of their distinct "classes":

var Board = (function() {
  var self = {};

  // settings for board
  self.options = {
    debug: true,
    addedPlayTiles: function() {},
    clearedPlayTiles: function() {}
  };

  // set to true once the board has been setup
  self.isSetup = false;

  // quick access to square elements
  self.squares = {};
  self.squareCount = 0;

  self.setup = function(options) {
    self.log("Setting up board!");

    // set options
    _.each(options, function(val, key) {
      self.options[key] = val;
    });

    return self;
})();

Some code from the middle has been omitted but this should give you the general idea.

  1. What is the purpose of the the following: (function() { // code })(); Is this the module pattern that I've seen talked about? Is this meant to keep the global namespace clean?
  2. What does this line mean?: var self = {} Is the self object used to exposed 'public' members? How would you define a private function or variable?
  3. How would you instantiate multiple "Boards" if you wanted to?
Share Improve this question asked Sep 7, 2010 at 18:55 MithraxMithrax 7,80720 gold badges57 silver badges61 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

It's called the Module Pattern.

The parentheses around the function mean it's being evaluated immediately after being defined -- so in essence it's a Singleton. Since it's an anonymous function, the definition is not stored - so you cannot readily create new instances of this object without a few modifications (which will be discussed later).

You are correct, self contains the "public" methods and properties, as it were. Any variables that aren't defined in self are not visible to the outside because of the closure properties. However, any functions defined in self still have access to the private variables because in Javascript, functions maintain access to the context (including variables) in which they were defined -- with a few exceptions.. mainly arguments and this.

If you want to define multiple instances of this object, you would remove the parentheses (var Board = function () { ... }) and then use var obj = Board() to create an object. Note that it does not use the new operator.

As mentioned in the other answer, that's the Module Pattern.

It is also known as the YUI Module Pattern or the Yahoo Module Pattern, mainly because it was made popular by this blog article:

  • YUI Blog: A JavaScript Module Pattern by Eric Miraglia

Regarding point 3, the Module Pattern is intended to be a singleton. However, the Module Pattern is easily transformed into a Constructor Pattern. You may want to check out the following presentation by Douglas Crockford for more information on this topic:

  • JavaScript: The Good Parts - Functional Inheritance [PPT] by Douglas Crockford

var self = {} should have the effect of initializing self as an empty object literal; if self already existed, it should delete the old values and reinitialize as an empty array.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>