如何从另一个类的类访问方法? [英] How to access a method from a class from another class?

查看:82
本文介绍了如何从另一个类的类访问方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaScript中使用面向对象编程技术但我无法从另一个类的一个类访问方法。如何做到以下几点?

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

我收到以下错误:


Uncaught SyntaxError:意外的标识符 - >> for var object = new one();


推荐答案

您的语法不合法。您的控制台中应该出现错误,显示哪行代码不正确。

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

对于非静态情况,你不需要有正确的语法。您似乎想要在两个的构造函数中创建 One 对象的实例,如下所示:

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

注意:我也遵循使用以大写字母开头的标识符的常见Javascript约定对于类/构造函数名称,例如一个而不是一个

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.

这篇关于如何从另一个类的类访问方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆