在JavaScript中使用类
作为初学者,我尝试使用JavaScript类,因为我开始学习使用C#编程 所以我想将一个注释(带有标题和文本)存储到数据存储中。这些是我的小班:在JavaScript中使用类,javascript,class,web,Javascript,Class,Web,作为初学者,我尝试使用JavaScript类,因为我开始学习使用C#编程 所以我想将一个注释(带有标题和文本)存储到数据存储中。这些是我的小班: class Note{ // The single note constructor(noteTitle, noteText) { // set the notes title and text title = noteTitle; text = noteText; } var title; var text; }
class Note{ // The single note
constructor(noteTitle, noteText) { // set the notes title and text
title = noteTitle;
text = noteText;
}
var title;
var text;
}
class Notestore{
var notes = []; // stores all the notes
function AddNote(note){
notes.push(note); // add a new note to the list
}
}
class NoteController{
var store = new NoteStore(); // get the reference to the store
function CreateNote(title, text){ // create a new note and store it
store.AddNote(new Note(title, text));
}
}
所以当我启动应用程序时,它会说
var store = new NoteStore();
没有定义。我的NoteController是第一个被调用的类。我必须改变什么,我的类才能工作=
谢谢你的帮助 首先,您调用您的类Notestore。然后,您尝试将其用作带有大写字母S的NoteStore。您在Javascript中如何使用实例变量/类属性方面犯了错误。您需要将它们分配给
this
(例如this.foo='bar'
)。您在声明方法时也犯了一些错误,您不需要使用函数
关键字。这是您的代码,已更新以正确使用实例变量:
class Note { // The single note
constructor(noteTitle, noteText) { // set the notes title and text
this.title = noteTitle;
this.text = noteText;
}
}
class NoteStore {
constructor() {
this.notes = []; // stores all the notes
}
AddNote(note){
this.notes.push(note); // add a new note to the list
}
}
class NoteController {
constructor() {
this.store = new NoteStore(); // get the reference to the store
}
CreateNote(title, text){ // create a new note and store it
this.store.AddNote(new Note(title, text));
}
}
var store = new NoteStore();
Javascript是一种区分大小写的语言。试着改变
class Notestore{
...
}
到
1.您不能在类中声明字段。因此,删除
var标题代码>和其他。2.您可以使用this.
来处理实例属性,而不仅仅是名称。实际上,您可以运行代码是令人惊讶的,因为它在语法上是不正确的。NoteStore!==Notestore
-这只是很明显的类型,可能是重复的,解决了,然后还要补充一点,OP应该使用camelcase名称作为其方法,即addNote和createNote-而不是addNote和createNote。你是对的,这是当前将camelcase用于JS变量的趋势,函数和方法以及类名称的大写字母。我认为这种大写字母在C#,Go和其他一些语言中很常见/流行。我只是在发布之前更正了它,但是有一份旧的代码副本对不起,我只是在发布之前更正了它,但是有一份旧的代码副本
class NoteStore{
...
}