3

I have a function onChangeBrand() in A.js and there is a same name in B.js.

So how to avoid this situation? There is a constraint - I can't change the function names. and i am not allowed to edit both the Js files so namespace is not a right idea for me.

Can we call something like A.onChangeBrand() or B.onChangeBrand()?

outis
  • 75,655
  • 22
  • 151
  • 221
BOSS
  • 2,931
  • 8
  • 28
  • 53

4 Answers4

1

Check how to use namespaces in JavaScript if you can edit these two files a.js and b.js then you can declare namespaces. See best answer here : How do I declare a namespace in JavaScript?

Community
  • 1
  • 1
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
1

Ok, if namespaces are not for you and you can put your code in between the script tags loading these files

<script src='a.js'></script>
<script>
var a_onChangeBrand = onChangeBrand; // copy the function
</script>
<script src='b.js'></script>

after that a_onChangeBrand() will call the function from a.js and onChangeBrand() from b.js

But nothing will help you if some functions in those a.js and b.js are also using these functions - they might call function from the last file loaded.

Cheery
  • 16,063
  • 42
  • 57
1

If you don't have access to the source, then the following is a solution (not the prettiest, mind you):

<script src="http://exmpale.com/a.js"></script>
<script>
 A = { onChangeBrand:onChangeBrand };
</script>

<script src="http://exmpale.com/b.js"></script>
<script>
 B = { onChangeBrand:onChangeBrand };
</script>

The two functions are now namespaced and can be invoked like so:

A.onChangeBrand();     
B.onChangeBrand();
osahyoun
  • 5,173
  • 2
  • 17
  • 15
0

You can do this to one of your function..

var myNS = new (function() {

    this.onChangeBrand= function() {
        alert('hello!');
    };

})();

and then call myNS.onChangeBrand();

Similarly use myNS2 for other function. These are called as namespaces.

Shashank Kadne
  • 7,993
  • 6
  • 41
  • 54