简体   繁体   中英

How to Properly Access Class Properties in Javascript

I have this class definition:

$.note = function() {}
$.note.prototype = {
  init: function(note) {
    this.note = note;
    this.ctrl = document.getElementById(note);
  },
  // I have these getter functions because I was getting errors using
  // myObject.note or myObject.ctrl
  getNote: function() {
    return this.note;
  },
  getCtrl: function() {
    return this.ctrl;
  }
}

I created a new object with this class like this:

var note = new $.note('C');

Which I can access in my console like this: 注意

But when I try and access note.getNote(), I get undefined as the response: 在此处输入图片说明

Am I going about accessing these properties incorrectly? I've tried using just note.note or note.ctrl, and I get the same thing...

Nothing's going to call that "init" function if you don't.

$.note = function(note) { this.init(note); }

Some frameworks provide an object system that uses constructor helper functions like that, but plain JavaScript doesn't.

Try this:

$.note = function(note) { this.note = note;}

or you should call init function:

var note = new $.note();
note.init('C');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM