JavaScript 代码在回调中不起作用

标签 javascript

在以下 JavaScript 代码中,如果 warnBeforeNew 为 false,则文件打开代码有效。但是,如果 warnBeforeNew 为 true,则不会,而是给出错误“Uncaught TypeError:无法读取未定义的属性“root””。

我不知道这是否与范围有关,但是如何让文件加载代码在回调中工作?谢谢。

Editor.prototype.open = function(path) {
  if (Editor.warnBeforeNew==true){
    this.showDialog({
        dialogLabel: 'You have unsaved changes. Are you sure you want to discard them and open a different file?',
        submitLabel: 'Discard',
        cancelLabel: 'Cancel',
        submitCallback: function() {
          Editor.warnBeforeNew=false;
          this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
        }
    });
  } else {
    this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
  }
};

最佳答案

您必须保存 this 的值,因为调用回调时,它使用与外部函数不同的接收器:

if (Editor.warnBeforeNew==true){
    var thing = this; // choose a more meaningful name if possible...
    this.showDialog({
        dialogLabel: 'You have unsaved changes. Are you sure you want to discard them and open a different file?',
        submitLabel: 'Discard',
        cancelLabel: 'Cancel',
        submitCallback: function() {
          Editor.warnBeforeNew=false;
          thing.filesystem.root.getFile(path, {}, thing.load.bind(thing), error.bind(null, "getFile " + path));
        }
    });
  } else {
    this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
  }

关于JavaScript 代码在回调中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18299254/

相关文章:

javascript - 将没有键的值推送到 javascript 数组

javascript - Eslint 无法读取配置文件

javascript:获取印度的日期和时间(不是个人计算机的日期和时间)

javascript - Uncaught TypeError : this. state.data.map 不是函数

javascript - 从哪里 Javascript 错误 "ReferenceError: Can' t 找到变量 : imenu_title"?

javascript - jQuery 动态点击

javascript - 使用隐式流程时的重放攻击

javascript - 如果我有多个 ul 并且所有 li 都有相同的类名,我怎样才能获得特定于 ul 的 li

javascript - 快捷编程语言我错过了什么吗?

javascript - 找不到为导入语句抛出的规则 'jsx-a11y/img-has-alt' 的定义