繁体   English   中英

Javascript闭包(使用参数名称在同一函数中定义对象)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM