I want to use Object Oriented Programming technique with JavaScript but I can't access a method from one class from another class. How can do like the following?
class one{
write(){
console.log("Yes! I did!");
}
}
class two{
var object=new one();
tryingMethod(){
object.write();
}
}
I get the following error:
Uncaught SyntaxError: Unexpected identifier -->> for
var object=new one();
What I'd recommend doing is not tying the classes together so tightly and doing something like this...
Now what you can do is...
This allows you to have a better separation of concerns and allows you to more easily unit test the
Two
class because you can pass in a mock implementation of theOne
class if you want.Your syntax is not legal. There should be an error in your console showing you which line of code is not correct.
If it's a static method (doesn't use any instance data), then declare it as a static method and you can directly call it.
If it's an instance method, then you would typically create an object of type
one
and then call the method on that object (usually in the constructor).To make the method static (which appears to be fine in your specific case):
For the non-static case, you don't have the proper syntax. It appears you want to create the instance of the
One
object in a constructor forTwo
like this:Note: I'm also following a common Javascript convention of using an identifier that starts with a capital letter for the class/constructor name such as
One
instead ofone
.