tags:

views:

38

answers:

2

I have two methods with the same name, for different purposes in 2 different .js files. How can I use those methods on same page?

In Count.js:

function add()
{
// some manipulation doing here
}

In PriceImplement.js

Function add()
{
// some manipulation doing here
}
+6  A: 

If they're both defined using function declarations, like

function iHaveTheSameNameAsAnotherFunction(params) {
    …
}

then you can't. The second declaration will simply overwrite the first one.

Marcel Korpel
is there any way to implement? can i create class in javascript and use them?
Pankaj
@Pankaj: Can you change one of those files (or both, so you can change the function name)?
Marcel Korpel
@@ thanks Marcel...i can change function name.but can i create class in javascript and use them?
Pankaj
@Pankaj: Yes, see Machine's answer.
Marcel Korpel
+5  A: 

You should get into the habit of namespacing your JavaScript-files:

//Count.js:

var Count = {
  add: function add() {
  },
  [additional methods in the Count object]
};

// PriceImpl.js

var Price = {
  add: function add () {
  },
  [additional methods for the Price implementation]
};

Then call methods like Namespace.method, i.e. Price.add()

PatrikAkerstrand
Don't forget to **not** use a trailing comma after the last function/property! Otherwise you'll be quarreling with IE. And just to add: Machine is using [named function expressions](http://yura.thinkweb2.com/named-function-expressions/#named-expr) here, which makes debugging a bit easier.
Marcel Korpel