Short answer:
This is the "normal" JavaScript behavior. The language has advanced and it is now possible to use const
to declare constants that can not be overwritten.
Elongated response:
From the beginning, JavaScript allows you to overwrite variable names and functions, and even assign values to variables without declaring them, "declaring them" in global scope, which has generated bugs that are difficult to detect.
In modern versions of JavaScript a lot of this has been fixed and for you the fix is to use const
, assigning a variable a function.
So in ECMAScript 2015 (version 6 of JavaScript) there is const
that starts a variable that can not be overwritten without generating a compilation error.
Your questions:
This is actually the expected behavior when we declare 2
methods with the same name and parameters in js, it will always
override and will the last one declared prevail?
Yes. Unless you use const
(which will generate an error if the names are the same). This is normal behavior, just like CSS, the last to be declared pervalece.
Is there any explanation for this behavior, if so what is this?
explanation?
This is how the language was built, a flexible medium ... But it is being strengthened / corrected in the new versions.
Is there any way to make it generate any errors or something
if someone makes this mistake and declares 2 methods with the same
name and parameters?
Yes, using const
, the problem is corrected. That is, it gives an error if a variable is overwritten. In this case you can use:
const teste = function(){
console.log('teste 1');
}
and if you then do const teste = outra coisa...
the compiler gives error and does not run.
If 3 has some way to do it, what to do if the functions
are in different js files?
In this case you have to encapsulate things. Or you use CJS, AMD, or ES6 modules. There is not yet a universal specification on the part of the language, but there are proposals that are in analysis in this sense. If you use the Babel compiler you can already use these modules.
So there are two answers:
With compiled modules you can declare everything in the "global" scope because the module does not share that scope with other files. All variables are encapsulated and the only thing you can export out of the module is via the reserved word exports
. An example:
function teste(){
console.log(1);
}
module.exports = teste;
This way teste
is not visible to other files.
Using native JavaScript, where all files share global space:
Here you have to encapsulate your own things. The concept is identical but you have to use IIFEs to hide the variables of each other.
For example:
// ficheiro A
(function(global) {
function teste() {
console.log('teste A');
}
global.testeA = teste;
})(this);
// ficheiro B
(function(global) {
function teste(nr) {
var res = nr * nr;
console.log('teste B', res);
}
global.testeB = teste;
})(this);
testeA();
testeB(17);