That’s a object literal being passed as argument to an initializer function.
A literal is a way of defining/constructing a data structure in the program’s own source code, rather than through a series of calls and/or the explicit definition of a type/class. Example:
var obj = {
budget: {
// the key is the metric id
'loadTime': {
max: 200
},
'redirectCount': {
max: 1
},
'globalJS': {
min: 2,
max: 5
}
}
};
Is equivalent to:
var obj = new Object();
obj.budget = new Object();
obj.budget.loadTime = new Object();
obj.budget.loadTime.max = 200;
...
This literal format is commonly referred to as JSON, but in reality they are different concepts (JSON is a format of text, inspired by Javascript objects, but more restricted in format and more general in application).
// É um texto, não um literal; e repare no uso obrigatório das aspas duplas
var meuJSON = '{ "budget": { "loadTime": { "max": 200 }, "redirectCount": { "max": 1 }, "globalJS": { "min": 2, "max": 5 } } }';
var obj = JSON.parse(meuJSON); // Cria o mesmo objeto definido acima
The passage of a complex object as a function argument is commonly used for:
Pass optional parameters - if your function works well in a "standard" way but there are many little details that the programmer may or may not want to adjust, so instead of a huge list of parameters it is preferable to accept an object and read from it these optional parameters. This makes it more convenient to be invoked;
Operating on a generic data structure - in this case, it would be the same to pass a literal or an object contained in a variable. Only if you will not use this object after outside the function context, it is not necessary to create it and use it in two different steps, you can do everything in one operation only (it helps to "depoluize the namespace").
What is your method init
is doing, I don’t know, but by the way is a mix of one or the other (i.e. several of these arguments seem necessary to me, but not all, so receiving an object allows the programmer to choose what to pass to function without having to keep repeating null
, null
, null
for all parameters that do not apply).
"when I am using some external file" Sorry, I don’t understand, what would this external file be? You are simply saying that the script that defines
perfBar
is in a different file than the one that uses it (and if so, it is irrelevant, every JS on the page runs under the same context) or is something else?– mgibsonbr