JavaScript - Persistent data in function between calls?

╄→гoц情女王★ 提交于 2021-01-24 13:48:08

问题


I want to call a function with an argument and store the value so that next time I call that function without arguments it uses the last argument that was set. Is this possible with JavaScript?

Edit: Here's more info on what I'm trying to achieve...

var track = 0;
$.getJSON('songsMetadata.json', function(data){
    appendData(data);
});
player.bind("ended", function(){
    track++
    appendData();
});
function appendData(data){
    /* Here I want to populate 
     the inside 'data' argument 
    only once (in the callback of 
    getJSON) and use that same
    data in the 'player.bind' 
    callback */

    //Some code to append data[track] to an HTML list
}

回答1:


You need to keep a reference to the last acceptable argument in the enclosing scope. For example:

var ref;

function foo (arg) {
  if (!arg) { // or arg === undefined if you want to be safe
    arg = ref;
  } else {
    ref = arg;
  }

  // actual function behavior here
  console.log(arg);
}

foo(); // undefined
foo(2); // 2
foo(); // 2
foo(3); // 3
foo(); // 3

If you want to repeat this behavior, you might want to consider writing a wrapper function to cache an accepted function's argument. For example:

function cacheFn (fn) {
  var ref;
  
  return function (arg) {
    if (!arg) {
      arg = ref;
    } else {
      ref = arg;
    }
    
    return fn(arg);
  }
}

function foo (arg) {
  console.log(arg);
}

var cachedFoo = cacheFn(foo);

cachedFoo(2);
cachedFoo();
cachedFoo(3);
cachedFoo();



回答2:


In a more general way:

function enclose(func) {
 let args = [];
 return function (...passed) {
   if(passed.length) args = passed;
   func(...args);
 };
}

Usecase:

const log = enclose(console.log.bind(console));
log(5,1);
log();


来源:https://stackoverflow.com/questions/44477420/javascript-persistent-data-in-function-between-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!