访问JS对象's成员或方法,从同一对象

accessing JS object's member or method, from within the same object

本文关键字:对象 方法 JS 访问 成员      更新时间:2023-09-26

我有以下脚本,其中我试图为应用程序创建一个配置对象:

  var myConfig = {
  localDBAllowed: function () {
      return window.openDatabase;
  },
  MessageBox: function (message, title) {
      if (navigator.notification) {
          navigator.notification.alert(message, null, title, 'OK');
      } else {
          alert(message);
      }
  },
  initializeDb: function(){
      if (localDBAllowed) {
          messageBox('local db allowed', '');
      } else {
          messageBox('local db not allowed', '');
      }
  }
  };
  myConfig .initializeDb();

我得到的错误是localdallowed没有定义。从行:if (localDBAllowed) {

我的问题是如何从同一对象内访问对象的成员/方法。我尝试使用这个关键字,没有成功,如下所示:

 if (this.localDBAllowed) {
            messageBox('local db allowed', '');
this.localDBAllowed

将不返回任何值,尝试

this.localDBAllowed()

这个适合我。(一语双关)

var myConfig = {
  localDBAllowed: function () {
      return window.openDatabase;
  },
  messageBox: function (message, title) {
      if (navigator.notification) {
          navigator.notification.alert(message, null, title, 'OK');
      } else {
          alert(message);
      }
  },
  initializeDb: function (){
      if (this.localDBAllowed) {
          this.messageBox('local db allowed', '');
      } else {
          this.messageBox('local db not allowed', '');
      }
  }
};
myConfig .initializeDb();

我所做的只是将this标识符添加到对象内调用函数或变量的区域。