Because of scope. The problem doesn't have anything to do with whether it's desktop or mobile — for example, I just ran the same code in Firefox, Safari, and Chrome on the same computer and got SHOULD NOT SEE THIS ALERT
on Safari. You have two functions with the same name in the global scope, so which function is actually SameName
probably depends on the JS engine implementation details.
If you wanted to define these functions in a way that didn't pollute the global (or parent, if this were in another function) scope, you could use const or let bindings, but then you wouldn't be able to call the function, because those use block scope rather than function scope:
if (test_one_condition) {
const SameName = () => {
alert('SEE THIS ALERT');
}
}
if (test_two_condition) {
// or with `let`
let SameName = () => {
alert('SHOULD NOT SEE THIS ALERT');
}
}
SameName();
// SameName is not defined
If you wanted to change the result of a function with the same name, you could declare it with a let or var, then assign it in the conditionals:
let SameName
if (test_one_condition) {
SameName = () => {
alert('SEE THIS ALERT');
}
}
if (test_two_condition) {
SameName = () => {
alert('SHOULD NOT SEE THIS ALERT');
}
}
SameName();
And just in case anyone comes across this question at some point and gets the impression that defining functions based on a condition using names in the global scope would be a good way to do things, deciding what action to take in the function would of course be a better way to go about it:
const sameName = (cond) => {
const msg = cond ? 'SEE THIS ALERT' : 'SHOULD NOT SEE THIS ALERT'
alert(msg)
}
sameName(someCondition)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…