Javascript:缓存的函数属性vs新值

时间:2015-08-20 14:58:20

标签: javascript function

基本功能:

function myStuff(a,b,c){
    var _c = _c || c || {};
    console.log(_c);
}

如果之前使用过,则使用缓存值,如果是新的/不同的话,则使用新值。

问题是:如果函数调用不包含第三个属性,为什么console.log(_c)显示未定义或如何更好地编写此行var _c = _c || c || {};

由于

4 个答案:

答案 0 :(得分:2)

the scope of the variable you defined is the function itself, therefore, it is redefined every time you call the function.

the correct way to cache a variable, is to define it in the parent scope of the function:

var _c;
function myStuff(a,b,c){
    _c = c || _c || {};
    console.log(_c);
}

read more about js scopes here: What is the scope of variables in JavaScript?

的元素子元素

答案 1 :(得分:1)

您可以将缓存存储在函数本身

function myStuff(a,b,c){
    if (!myStuff.cache) {
        myStuff.cache = {};
    }

    var cache = myStuff.cache;
    c = cache.c = cache.c || c || {};

    console.log(c);
}

答案 2 :(得分:1)

如果您想访问_c外部值,则必须使用以下函数:

function myStuff(a,b,c){
    var _c = window._c || c || {};
    console.log(_c);
}

答案 3 :(得分:1)

我想。使用此代码if ( c === undefined ) { c = {}; }解决了未定义c

的问题
function myStuff(a,b,c){
  if ( c === undefined ) { c = {}; }
  var _c = _c || c || {};
  console.log(_c);
}

因为

_c = c || _c || {};

不计算{}的最后一个案例。