Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 13th, 2012  |  syntax: None  |  size: 1.40 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. var f1, // カリー化っぽく
  2.     f2, // new 演算子を使ってオブジェクトを作る
  3.     f3, // オブジェクトを返す関数を作って
  4.     f4; // Number.prototypeを使う
  5.  
  6. f1 = function () {
  7.     var add = function (a) {
  8.         return function (b) {
  9.             return _add(a, b);
  10.         };
  11.     };
  12.  
  13.     var n = add(1);
  14.     test(n(2), 3);
  15. };
  16.  
  17. f2 = function () {
  18.     var add = function (a) {
  19.         this.a = a;
  20.         this.add = function (b) {
  21.             return _add(this.a, b);
  22.         };
  23.     };
  24.  
  25.     var n = new add (3);
  26.     test(n.add(4), 7);
  27. };
  28.  
  29. f3 = function () {
  30.     var add = function (a) {
  31.         return {
  32.             add : function (b) {
  33.                 return _add(a, b);
  34.             }
  35.         };
  36.     };
  37.  
  38.     var n = add(5);
  39.     test(n.add(6), 11);
  40. };
  41.  
  42. f4 = function () {
  43.     if (! Number.prototype.add) {
  44.         Number.prototype.add = function (b) {
  45.             return _add(this,b);
  46.         };
  47.  
  48.         var n = 7;
  49.         test(n.add(8), 15);
  50.     }
  51. };
  52.  
  53. f1();
  54. f2();
  55. f3();
  56. f4();
  57. test((9).add(10), 19);
  58.  
  59.  
  60. /* Functions */
  61.  
  62. function test (result, forecast) {
  63.     var is_success = (result === forecast) ? 'success:' : '! failed:';
  64.     console.log([is_success, result, forecast].join(' '));
  65. }
  66. function toNumber (n) {
  67.     return (typeof n === 'number') ? n
  68.          : (Number(n))             ? Number(n)
  69.          :                           0;
  70. }
  71.  
  72. function _add (a, b) {
  73.     return toNumber(a) + toNumber(b);
  74. }