function myStuff(a,b,c){
var _c = _c || c || {};
console.log(_c);
}
的想法是使用緩存的值,如果之前使用,或者在新的/不同的新的價值。
現在的問題是:如果函數調用不包含第三個屬性,爲什麼console.log(_c)
顯示未定義或我該如何寫這行var _c = _c || c || {};
更好?
感謝
function myStuff(a,b,c){
var _c = _c || c || {};
console.log(_c);
}
的想法是使用緩存的值,如果之前使用,或者在新的/不同的新的價值。
現在的問題是:如果函數調用不包含第三個屬性,爲什麼console.log(_c)
顯示未定義或我該如何寫這行var _c = _c || c || {};
更好?
感謝
我想通了。有了這個代碼if (c === undefined) { c = {}; }
解決了不確定c
問題:
function myStuff(a,b,c){
if (c === undefined) { c = {}; }
var _c = _c || c || {};
console.log(_c);
}
因爲
_c = c || _c || {};
不計爲{}
最後一種情況。
你定義的變量的作用域是函數本身,因此,它被重新定義每次調用該函數的時間。
緩存變量正確的方法,是在功能的父範圍來定義它:
var _c;
function myStuff(a,b,c){
_c = c || _c || {};
console.log(_c);
}
閱讀更多關於JS範圍在這裏:What is the scope of variables in JavaScript?
您可以將內部高速緩存函數本身
function myStuff(a,b,c){
if (!myStuff.cache) {
myStuff.cache = {};
}
var cache = myStuff.cache;
c = cache.c = cache.c || c || {};
console.log(c);
}
如果YOUT要訪問_c
對外價值,你必須使用該函數是這樣的:
function myStuff(a,b,c){
var _c = window._c || c || {};
console.log(_c);
}
只在第一個電話。在那之後它被緩存了 – MoLow
但是||的部分當使用沒有第三個屬性的函數時忽略{}。 – thednp
不是由我。你使用哪種瀏覽器? – MoLow