run 2 identical javascripts on the same page
This is a general question. I have a javascript i want to use twic开发者_C百科e on the same page. It is obvious that whenever i interact with one of them - it will change the other one. I know that renaming method names within them will solve this, but i don't have access to it. Is there a way to let them both work without collision between the 2 of them?
I thought of wraping each of them inside a javascript with other name, but i am stuck here. Any ideas?
This is a design problem.
The best way to tackle this is to design the code in the object orientated way, with JS classes (I know a lot of people will tell me that JS has no classes, but it does for all intents and purposes).
For example:
// Define the class
function myobject() {
// Variables belonging to this class
this.value1 = 0;
this.value2 = 0;
this.total = 0;
// A function within this class
this.addNumbers = function(){
this.total = this.value1 + this.value2;
}
}
// Create two instances of the class
var mything = new myobject();
var mything2 = new myobject();
// Set variables within the instances
mything.value1 = 5;
mything2.value1 = 10;
// Run the function
mything.addNumbers();
mything2.addNumbers();
// Show the result
alert(mything.total);
alert(mything2.total);
You now have two instances of myobject which will not conflict with each other. This class can also have functions inside of it.
So in your case, it might be worth wrapping the JS you have inside a class, then creating instances of that class.
document.scripts[Name - or - index].method()
OR Load in different documents. i.e., load second script in iframe document and use it.
精彩评论