0

I have multiple .js file linked on the page that have functions with the same name like following mockup

first.js

function DisplayContent(data,$target) // data is string
{
     $target.html('<span>'+ data +'</span>')
}

second.js

function DisplayContent(data,$target) // data is string
{
     $target.html('<div>'+ data +'</div>')
}

Both the above files are referred to the page.

How to can i fix the above issue without renaming the functions.

Please correct if approach is wrong.

Thanks

Mayank
  • 1,291
  • 5
  • 21
  • 38

5 Answers5

3

you could use namespacing in JavaScript files:

first.js:

var first= {
  DisplayContent: function DisplayContent(data,$target) 
  {
     $target.html('<span>'+ data +'</span>')
  },
     [additional methods in the first object]
};

second.js

var second= {
  displayContent: function DisplayContent(data,$target) 
  {
      $target.html('<div>'+ data +'</div>')
  },
  [additional methods for the second implementation]
};

Then call methods like Namespace.method, i.e. first.DisplayContent()

Vibhesh Kaul
  • 2,582
  • 1
  • 18
  • 37
1

It would be better i guess

function DisplayContent(data,$target,htmltag) // data is string
{
     $target.html('<' + htmltag + '>' + data + '</' + htmltag + '>')
}
Arif
  • 1,567
  • 8
  • 18
1

If you are calling these function only in that file itself then you can limit scope like this:

First.js

(
  function(){
    function DisplayContent(data,$target) // data is string
    {
         //$target.html('<span>'+ data +'</span>')
         alert("first file");
    }

    DisplayContent('test','test');

    //here you can place other code
}());

Second.js

(
  function(){
    function DisplayContent(data,$target) // data is string
    {
         //$target.html('<div>'+ data +'</div>')
         alert("Second file");
    }

    DisplayContent('test','test');

    //here you can place other code
  }()
);

See a demo

Manwal
  • 22,994
  • 11
  • 59
  • 91
0

Multiple ways.

  1. You can do this in your second.js, if you dont want them to confict. This will let you use second.js independently in a page and this function would fire.

     if(typeof DisplayContent !=='function'){
        function  DisplayContent(){
    
      }
     }
    
  2. You can go for a closure like Manwal rightly pointed.

However, having two functions with the same name, doesn't make much sense. You should avoid this.

Bhargav Ponnapalli
  • 8,826
  • 7
  • 33
  • 44
-1

If you add two JS files to a single page, both files will run in a single javascript context and the functions will be replaced making the result un acceptable. Thus making is impossible to do your requirement.

Imesh Chandrasiri
  • 5,428
  • 13
  • 56
  • 101