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()?

6
  • Are you able to put your js code on the page between the script tags loading these files? Commented Feb 10, 2012 at 7:16
  • Yes @Cherry i am taking them in my src Commented Feb 10, 2012 at 7:18
  • My nickname is slightly different. And the second question - do these functions have calls from those files or only you are using them? Commented Feb 10, 2012 at 7:20
  • This has nothing to do with Java. Please read the description of tags applied to posts. Commented Feb 10, 2012 at 7:27
  • @Cheery, those are part of some API .So apart from me other guys are also using them. Commented Feb 10, 2012 at 7:41

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is Something out of the box thought. Thanks @Cheery
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?

Comments

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();

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.