It's just for easy typing when you're going to access multiple members of an object.
As your example shows you can only type nome
and you did not have to type obj.nome
to access the member.
The gain is very small and it can cause ambiguity problems so its use is not recommended. Consider it as something non-existent in language. Of course you can use in some case where it is clear there is no ambiguity and you will access many members of an object of a very long name, but still the gain is very small.
Ambiguity can occur because you no longer know if you are accessing a local variable (including parameter), global, an existing property in the prototype, or if you are referring to a member of the object. Example using your object:
function f(nome, obj) {
with (obj) {
console.log(nome);
}
}
And now, what nome
will it use, the parameter or member of obj
? Note that it gets worse if you have a global variable called nome
- although it should not have global variables.
If you have a very large object name and think that in addition to typing a lot (if you do not have an IDE that helps) or the text gets too large you can solve this by making the name very short. And it is called that saving the typing of o.
is important, it should rethink its coding criteria:
var o = objeto_de_nome_muito_grande_mas_que_nao_deveria_ter_sido_nomeado_assim;
console.log(o.nome);
Using with
:
with({o:objeto_de_nome_muito_grande_mas_que_nao_deveria_ter_sido_nomeado_assim}){
console.log(o.nome);
};
The examples are for demonstration purposes only. Obviously it's only worth doing this if you use the object several times.
As always, if you have good reason in a particular situation and are fully aware that there will be no problems there, you can even use them. In fact, some demonstrate with
good . This can be a legitimate way to use:
with({f:open("x.txt")}){
var data = f.read(1);
}
In strict mode is not possible use this syntax.
MDN Documentation .