23

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();

brasofilo
  • 25,496
  • 15
  • 91
  • 179
Hamdi Bayhan
  • 1,773
  • 4
  • 17
  • 20

3 Answers3

27

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):

class One {
  static write(){
    console.log("Yes! I did!");
  }
}

class Two {
   tryingMethod(){
     One.write();
   }
}

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 for Two like this:

class One {
  write(){
    console.log("Yes! I did!");
  }
}

class Two {
   constructor() {
       this.one = new One();
   }

   tryingMethod(){
     this.one.write();
   }
}

var x = new Two();
x.tryingMethod();

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 of one.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • He's calling it with an object, `object.write()`. Why does it need to be static? – Barmar Aug 26 '16 at 23:34
  • @Barmar - My answer clearly explains that he can go either way static or non-static depending upon whether the method uses instance data or not. His method does not access any instance data so I showed the static approach. I also added a corrected non-static example (OP had mistakes). – jfriend00 Aug 26 '16 at 23:35
  • @Barmar - I added a corrected example for the non-static case. – jfriend00 Aug 26 '16 at 23:38
  • @jfriend00 it's work for me, thanks. I want to ask a question Why did they give negative my question, where did i do wrong? – Hamdi Bayhan Aug 26 '16 at 23:49
  • @hamdi - Your code generates immediate errors and you appeared to not be aware of that. You should see those in the console yourself before you come here and you should either not be posting code that has errors in it or you should be including the exact error message and asking how to fix that specific error. That shows you did not do appropriate preparation or education before posting here which will often generate downvotes. – jfriend00 Aug 26 '16 at 23:52
  • @hamdi You just posted some code without explaining what it's supposed to do, what it's doing instead, etc. See http://stackoverflow.com/help/how-to-ask – Barmar Aug 26 '16 at 23:52
  • @Barmar and jfriend00 thanks for help, I right away read the rules. – Hamdi Bayhan Aug 27 '16 at 00:01
  • @jfriend00 A simple question please answer... what is the need of class? why do we create a class? – Ashh Aug 22 '18 at 13:20
  • 1
    @AnthonyWinzlet - Please read some references about "object oriented programming". Classes form the definition of objects which you can create and use. There are hundreds of uses and advantages of object oriented programming, including hundreds of books written on the subject. Going into detail on that is beyond the scope of a comment here and there are thousands of article references on the internet. You can start with [this one](https://codeburst.io/object-oriented-programming-in-javascript-51b2bdfdfe9f). – jfriend00 Aug 22 '18 at 17:50
4

What I'd recommend doing is not tying the classes together so tightly and doing something like this...

class One {
  write() {
    console.log("Yes! I did!");
  }
}

class Two {
  constructor(one = new One())  {
    this.one = one;
  }
  tryingMethod() {
    this.one.write();
  }
}

Now what you can do is...

const two = new Two();
two.write();

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 the One class if you want.

describe("two class", () => {
  it("should do something", () => {
    const one = {
      write: sinon.spy()
    };
    const two = new Two(one)

    two.tryingMethod();

    expect(one.write.calledOnce).to.be.ok;
  });
});
jcreamer898
  • 8,109
  • 5
  • 41
  • 56
0

You can pack dependencies in a container.

class Provider {
    private _one?: One;
    private _two?: Two;

    one(): One {
        return this._one || (this._one = new One(this));
    }

    two(): Two {
        return this._two || (this._two = new Two(this));
    }
}


class One {
    constructor(private provider: Provider) { }

    write() {
        console.log("Yes! I did!");
    }
}

class Two {
    constructor(private provider: Provider) { }

    tryingMethod() {
        this.provider.one().write();
    }
}
Filip Seman
  • 1,252
  • 2
  • 15
  • 22