天天看點

js回調函數的幾個執行個體

// Simple 1
var fn = new Function("arg1", "arg2", "return arg1 * arg2;");
var num = fn(2, 3);
console.log('第一個回調函數:結果=' + num);

// Simple 2
function fn2(arg1, arg2, callback){
  var num = Math.ceil(Math.random() * (arg1 - arg2) + arg2);
  callback(num);//傳遞結果
}

fn2(10, 20, function(num){
  console.log("Callback called! Num: " + num);
});

// Simple 3
function foo(){
  var a = 10;
  return function(){
    a *= 2;
    return a;
  };
}
var f = foo();
console.log(f()); //return 20.
console.log(f()); //return 40.

// Simple 4
var fs = require('fs')
  , menuPath = '../node-app/config/wechat-menu.json';

getJSONFronFile(menuPath, function(data) {
  console.log(data);
});

function getJSONFronFile(filePath, fn) {
  fs.readFile(filePath, function (err, data) {
    if (err) {
      console.log(err);
    } else {
      data = JSON.parse(data);
      return fn(data);
    }
  });
}