I have the below code. Need to know how "a" is used as a function parameter, and then inside the same function it again used as object "a" to call another function.And what is mean by "a || {}" at the end of code.
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
does probably add a function to the arg a
.
I can answer the a || {}; section
This is a way to check if "a" already exists. If it does then use it, if it doesnt the create it as a new object.
EDIT :
To answer your actual question (I originally thought you were having issues with the code), the a || {}
a || {}
part of the code says "either use 'a' or if 'a' is not defined then use a new empty object ({})".
ADVICE :
I would advise you return the a in your E.martin
method as objects in JavaScript are not hard referenced. If you don't return the result, you'll likely lose the original object that you sent to the method.
Let's say mergein
is a method that concatenates two objects:
function mergein(new_obj, old_obj){
for(var i in new_obj){
old_obj[i] = new_obj[i];
}
return old_obj;
}
If we have your original method, we will lose our original object keys/values when we get our result back:
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
If we return our a
object, we'll get back our original object with the added keys/values:
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.