[关闭]
@freeethy 2016-02-23T11:51:52.000000Z 字数 5696 阅读 1155

JavaScript Patterns

JavaScript


Essentials

avoiding globals

Literals and Constructors

Functions

function Summary

In JavaScript the knowledge and proper use of functions is critical. This chapter discussed the background and terminology related to functions. You learned about the

two important features of functions in JavaScript, namely:
1. Functions are first-class objects; they can be passed around as values and augmented with properties and methods.
2. Functions provide local scope, which other curly braces do not. Also something to
keep in mind is that declarations of local variables get hoisted to the top of the local
scope.
The syntax for creating functions includes:
1. Named function expressions
2. Function expressions (the same as the above, but missing a name), also known as
anonymous functions
3. Function declarations, similar to the function syntax in other languages

After covering the background and syntax of functions, you learned about a number
of useful patterns, which can be grouped into the following categories:

Object Creation Patterns

Namespace Pattern

This implementation is nondestructive, meaning that if a namespace exists, it won’t be re-created:

  1. var MYAPP = MYAPP || {};
  2. MYAPP.namespace = function (ns_string) {
  3. var parts = ns_string.split('.'),
  4. parent = MYAPP,
  5. i;
  6. // strip redundant leading global
  7. if (parts[0] === "MYAPP") {
  8. parts = parts.slice(1);
  9. }
  10. for (i = 0; i < parts.length; i += 1) {
  11. // create a property if it doesn't exist
  12. if (typeof parent[parts[i]] === "undefined") {
  13. parent[parts[i]] = {};
  14. }
  15. parent = parent[parts[i]];
  16. }
  17. return parent;
  18. };

This implementation enables all of these uses:

  1. // assign returned value to a local var
  2. var module2 = MYAPP.namespace('MYAPP.modules.module2');
  3. module2 === MYAPP.modules.module2; // true
  4. // skip initial `MYAPP`
  5. MYAPP.namespace('modules.module51');
  6. // long namespace
  7. MYAPP.namespace('once.upon.a.time.there.was.this.long.nested.property');
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注