2017-03-20 2 views
-1

초급으로 C#으로 프로그래밍을 배우기 시작했기 때문에 JavaScript로 클래스를 사용하려고했습니다.JavaScript에서 클래스 사용

그래서 (제목과 텍스트와 함께) 메모를 데이터 저장소에 저장하려고합니다. 나는 응용 프로그램을 시작할 때

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는 호출되는 첫 번째 클래스입니다. 나는 무엇을 바꾸어야 만하고, 수업은 효과가 있어야합니까?

도움 주셔서 감사합니다.

+2

1.

class Notestore{ ... } 

을 변경해보십시오. 따라서'var title;'과 다른 것들을 제거하십시오. 2. 'this.'를 사용하여 이름이 아닌 인스턴스 속성을 처리합니다. 구문 론적으로 올바르지 않기 때문에 실제로 코드를 실행할 수 있다는 것은 놀라운 일입니다. – zerkms

+0

'NoteStore! == Notestore' - 그리고 그것은 단지 명백한 오타입니다. –

+1

[JavaScript에서 클래스를 정의하는 데 사용할 수있는 기술은 무엇이며, 그 절충점은 무엇입니까?] (http://stackoverflow.com/ 질문/387707/what-techniques-can-be-use-class-in-javascript-what-are-their) –

답변

0

먼저 Notestore 클래스를 호출하십시오. 그런 다음 자본 S가있는 NoteStore로 사용하려고 시도합니다.

+0

죄송합니다, 방금 게시하기 전에 그것을 수정했습니다. ,하지만 코드의 이전 복사본을 가지고 – Garzec

2

Javascript에서 인스턴스 변수/클래스 속성을 사용하는 방법에 착오가 있습니다. 숫자를 this (예 : this.foo = 'bar')으로 지정해야합니다. 또한 메서드 선언에 대해 실수를 한 경우 function 키워드를 사용할 필요가 없습니다. 다음은 인스턴스 변수를 올바르게 사용하도록 업데이트 된 코드입니다.

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

또한 그 OP는 그들의 방법에 대한 camelcase 이름을 사용해야합니다, 즉 추가하고 싶습니다. addNote 및 createNote - AddNote 및 CreateNote가 아닙니다. –

+0

현재 JS 변수, 함수 및 메소드에는 camelCase를 사용하고 클래스 이름에는 UpperCamelCase를 사용하는 것이 맞습니다. 이 UpperCamelCase는 C#, Go 및 기타 다른 언어에서 많이 사용되는 것으로 생각합니다. –

0

자바 스크립트는 대소 문자를 구분합니다. 당신은 클래스에서 필드를 선언하지

class NoteStore{ 
    ... 
} 
+0

죄송합니다. 게시하기 전에 수정했지만 코드의 이전 복사본이 있습니다. – Garzec

관련 문제