In python you can just have file1.py with a class called "class1" like this:
class class1:
def __init_(self, var1, var2):
self.var3 = var1
self.var4 = var2
self.callFunction(self.var3, self.var4)
def callFunction(self, classVar1, classVar2):
print(classVar1)
print(classVar2)
def anotherFunction(self, otherVar1, otherVar2):
daString = otherVar1 + otherVar2
return daString
if __name__ == '__main__':
class1('passing var1', 'passing var2')
And we can import it in file2.py with:
from folder import file1
from folder.file1 import *
And we can then call file1.py class in file2.py and access literally everything in it, including updated self variables like this:
newThing = file1.class1('updated self var1', 'updated self var2')
# lets print our updated self vars from file1.py class
print(newThing.var3) # "updated self var1"
print(newThing.var4) # "updated self var2"
# lets call a function from file1.py's class and print result
result = newThing.anotherFunction('test', '123')
print(result) # test123
Pretty simple. Now my question is: how can this exact thing be done in node.js? My first failed attempt was this:
File1.js:
class Class1 {
constructor(var1, var2) {
this.cVar1 = var1;
this.cVar2 = var2;
this.extraThing = 'extra text';
someFunction(this.cVar1, this.cVar2); // wont work, it doesnt recognize someFunction()
}
someFunction(passArg1, passArg2) {
console.log(passArg1 + passArg2 + this.extraThing); // this.extraThing seems to be undefined, same with just extraThing
}
}
module.exports = new Class1();
Loading File1.js in File2.js:
const importClass = require('File1.js');
module.exports = async function(var1, var2) {
let classThing = new importClass(var1, var2); // will load, but unable to call a fnction inside of it
let var3 = 'something';
let var4 = 'else';
classThing.someFunction(var3, var4); // wont work, cant access someFunction (its undefined)
}
And my second failed attempt was abandoning the Class idea and just doing exports.Class1 = function (); in File1.js which would probably be even worse for what I'm trying to do.
I'm new to node.js so there's a very high chance that I'm doing something completely stupid and I'm aware of it.. but I've been searching on the internet for a long time and I can't seem to find what I'm looking for. Is what I'm looking for (the equivalent to how its done in python) even possible in node.js?
To rewrite the python code you provided to NodeJS — I'd do it like:
folder/file1.jsfile2.jswhich will give the exact same log result like in Python:
1- executing:
$ node file2.js2- executing directly:
$ node folder/file1.js(as "main")The updated values of the class properties are used within the Class itself by using
this. I.e:this.var3,this.callFunction()etc, just like you would do in Python usingself.From an imported (default) Class you create an instance using the
newkeyword, and than you use the variables and function methods using your instance namenewThing.var3,newThing.callFunction()etc.