on the same HTML file I want to import another JS file that overwrite some methods of MyClass (only some !!!!). How can I do that without doing a copy and past of the whole class ?
(I want to maintain the name MyClass as there are other JS files that I cannot modify that are using MyClass... )
I could... but I cannot as that class is used in files that I do not have access to...
my HTML import few js:
one.js
two.js
tree.js
one.js defines MyClass and two.js and tree.js uses MyClass.... I want to create file myfile.js to import between one.js and two.js that modify MyClass...
Ok, I tested modifying the object, instead of the class. In other words, create your class, then define the object by declaring, var myObject = new Class(); Once the object has been created, THEN can you modify it's methods. However, you cannot modify methods of the browser's existing objects and classes, such as the document object or the Element class. Anyway, here's how I do it:
Code:
//Construct our class
function MyClass(arg1) {
//Make your arguments accessible to outside functions
this.firstArgument = arg1;
this.methodA = function() {
alert(this.firstArgument);
}
}
//Define the object
var myObject = new MyClass("foo");
//Create a function to change the object instead of the class
function changeMethod() {
myObject.methodA = function() {
alert(myObject.firstArgument + " " + "bar");
}
}
//Returns "foo":
myObject.methodA();
changeMethod();
//Returns "foo bar":
myObject.methodA();
Thanks jamesbcox1980 , but it still doesn't do what I need... I need to overwrite a CLASS method... so that all the other JS that use obj = new MYCLASS() will work with my new class... I do not have controll on the other JS that uses the MYCLASS
But you can't do that. You can't modify a class without redefining the entire thing. And even that is a violation of strict code practices... I thought JS might be different, since I haven't played a lot with classes in JS, but that's not the case.
Honestly, this is a hack way of doing things, and you might rethink your methods.
Bookmarks