如何从另一个类的类访问方法?

编程入门 行业动态 更新时间:2024-10-09 18:25:04
本文介绍了如何从另一个类的类访问方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在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.

更多推荐

如何从另一个类的类访问方法?

本文发布于:2023-10-12 16:22:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485258.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!