[英]Javascript closure (using parameter name to define an object in the same function)
我有下面的代碼。 需要知道如何將“ a”用作函數參數,然后在同一函數內再次將其用作對象“ a”來調用另一個函數。代碼末尾的“ a || {}”是什么意思。
E.martin= function (a) {
a = mergein({ api_url: "/somefolder/",
json_parameter: false,
channel_id: null,
after_response_hook: null},
a || {});
//Here 'a' is a function arg
E.martin= function (a) {
//Here 'a' is overwritten by the returned value from mergein
a = mergein({ api_url: "/somefolder/",
json_parameter: false,
channel_id: null,
after_response_hook: null},
//Here 'a' is send to the function, if it's not null/false.
//if 'a' is null/false an empty object will be created and sent instead.
a || {});
mergein
可能確實向arg a
添加了一個函數。
我可以回答|| {}; 部分
這是一種檢查“ a”是否已經存在的方法。 如果使用,則使用它;如果不使用,則將其創建為新對象。
編輯 :
為了回答您的實際問題(我本來以為您在代碼中遇到了問題),請a || {}
a || {}
部分代碼表示“要么使用'a',要么如果未定義'a',則使用新的空對象({})”。
建議 :
我建議您在E.martin
方法中返回a,因為JavaScript中的對象不是硬引用。 如果不返回結果,則可能會丟失發送給該方法的原始對象。
假設mergein
是連接兩個對象的方法:
function mergein(new_obj, old_obj){
for(var i in new_obj){
old_obj[i] = new_obj[i];
}
return old_obj;
}
如果我們擁有您的原始方法,則在返回結果時,我們將丟失原始的對象鍵/值:
E.martin = function (a) {
a = mergein({ api_url: "/somefolder/",
json_parameter: false,
channel_id: null,
after_response_hook: null},
a || {});
}
var b = {foo:'bar'};
var result = martin(b);
console.log(result['foo']); // error
如果返回a
對象,我們將使用添加的鍵/值來返回原始對象:
E.martin = function (a) {
return mergein({ api_url: "/somefolder/",
json_parameter: false,
channel_id: null,
after_response_hook: null},
a || {});
}
var b = {foo:'bar'};
var result = martin(b);
console.log(result['foo']); // 'bar'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.