Java和JavaScript中的类之间的区别?

安德里奥

我对C#和Java有一定的经验,但是我正在尝试学习javascript / node.js。我不太清楚这段代码是什么问题。

所以我有我的main.js文件,它具有以下代码:

const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");

myclass.repeatString();

MyClass它调用了这个代码:

class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(myString);
    }
}

module.exports = MyClass;

当我尝试运行此方法ReferenceError: myString is not defined时,它会尝试执行该repeatString()方法。我做错了什么/做对的正确方法是什么?

nem035

与Java之类的语言不同,在Java中我们可以在不使用的情况下引用类中的变量,而在绑定中thisthis绑定的行为则与作用域不同。

在Java中,这是合法的:

class Test {
  int i;
  void method() {
    System.out.print(i); // <-- Java compiler knows to look for the `i` on the class instance (technically it first looks for `i` locally in the scope of `method` and the goes to look on the class)
  }
}

在JavaScript中,我们没有这种行为,没有类变量之类的东西(yet)。

class Test {
  i; // <-- Uncaught SyntaxError: Unexpected token ;
  method() {
    console.log(i);
  }
}

对于您的示例,这意味着您总是需要this在引用类中存在的变量时使用(技术上是在对象实例上)。

因此,您必须使用this.myString

repeatString() {
  console.log(this.myString);
}

之所以会这样,是Reference Error因为引擎试图myStringrepeatString和向上的范围中查找一个名为的变量并且没有任何变量唯一具有变量myString的作用域是构造函数中的作用域,并且该作用域无法从到达repeatString

JavaScript的类与Java完全不同(这里是概述),即使语法看起来非常相似。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章