Secret of the JavaScript Ninja 学习笔记 - 6

第四章 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;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值