Secret of the JavaScript Ninja 学习笔记 - 6

来源:互联网 发布:吉他谱编配软件 编辑:程序博客网 时间:2024/04/30 05:45

第四章 Wielding functions

4.3 Fun with function as objects

var fn = function() {};

The semicolon after function(){} is a good practice. When compressing code, properly placed semicolons will allow for greater flexibility in compression techniques.

var fn = function(){};fn.prop = "tanuki";

We can attach properties to a function.

4.3.1 Storing functions

We want to store a collection of related but unique functions, event callback management being the most obvious example. When adding functions, a challenge is determining which functions are actually new to the collection and should be added, and which are already resident and shouldn't be added. 
    var store = {      nextId: 1,            cache: {},            add: function(fn) {        if (!fn.id) {          fn.id = store.nextId++;          return !!(store.cache[fn.id] = fn);        }      }    };        function ninja() {};        store.add(ninja);    store.add(ninja);

Note: the !! construct is a simple way of turning any JavaScript expression to its Boolean equivalent.

4.3.2 Self-memoizing functions

Memoization is the process of building a function that's capable of remembering its previously computed values.
    function isPrime(value) {      if (!isPrime.answers) isPrime.answers = {};      if (isPrime.answers[value] != null) {        return isPrime.answers[value];      }      car prime = value != 1;      for (var i = 2; i < value; i++) {        if (value % i == 0) {          prime = false;          break;        }      }      return isPrime.answers[value] = prime;    }