为什么这个值传递给构造函数显示为undefined?
我有一些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()
方法时, ReferenceError: myString is not defined
。 我在做什么错了/什么是正确的方法来做到这一点?
与一些像Java这样的我们可以在一个类中引用variables而不使用this
语言不同, this
绑定在JavaScript中的performance与在范围上有很大区别 。
在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中,我们没有这种行为,没有类variables( 还 )的东西。
class Test { i; // <-- Uncaught SyntaxError: Unexpected token ; method() { console.log(i); } }
为了表明你指的是名为myString
的对象的属性,而不是名称相同的variables,你的console.log()
调用应该是:
console.log(this.myString);
要打印myString console.log(this.myString);
使用console.log(this.myString);
要访问一个类的variables,使用this
。 variables名。
请检查下面的代码。
class MyClass { constructor(myString) { this.myString = myString; } repeatString() { console.log(this.myString); } } const myClass = new MyClass('Hello'); myClass.repeatString();
JavaScript中的类成员variables可以使用this.member-variable语法来访问。
解决问题的正确方法如下:
Main.js
const MyClass = require("./MyClass"); let myclass = new MyClass("my string!"); myclass.repeatString();
MyClass.js
class MyClass { constructor(myString) { this.myString = myString; } repeatString() { console.log(this.myString); } } module.exports = MyClass;