Reputation: 2951
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()
?
Upvotes: 3
Views: 145
Reputation: 16214
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.
Upvotes: 1
Reputation: 5231
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();
Upvotes: 1
Reputation: 8101
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.
Upvotes: 0
Reputation: 44605
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?
Upvotes: 1