Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - How to access a method from a class from another class?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...