简体   繁体   English

如何正确访问Java类的属性

[英]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: 但是,当我尝试访问note.getNote()时,响应未定义: 在此处输入图片说明

Am I going about accessing these properties incorrectly? 我会错误地访问这些属性吗? I've tried using just note.note or note.ctrl, and I get the same thing... 我已经尝试只使用note.note或note.ctrl,但我得到了同样的东西...

Nothing's going to call that "init" function if you don't. 如果没有的话,什么也不会调用该“ init”函数。

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

Some frameworks provide an object system that uses constructor helper functions like that, but plain JavaScript doesn't. 一些框架提供了使用这样的构造函数帮助器函数的对象系统,但是普通的JavaScript却没有。

Try this: 尝试这个:

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

or you should call init function: 或者您应该调用init函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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