【问题标题】:Why do I get "Uncaught ReferenceError: this is not defined" in my class constructor? [duplicate]为什么在我的类构造函数中出现“未捕获的 ReferenceError:未定义”? [复制]
【发布时间】:2017-06-17 05:24:50
【问题描述】:

背景

我正在制作一个 Chrome 扩展程序,它会在页面重新加载后打印日志。我的所有功能都在一个错误页面中,所以最近我决定让我的代码可读并使用classes 重构它。

问题

我设法让我的扩展程序启动并运行,但现在,每次加载页面时,都会出现很多错误。

也就是说,我在我的猫的构造函数中得到了Uncaught ReferenceError: this is not defined 的错误!

init.js

"use strict";
window.onload = function() {
  let cat = new Cat("Boby");
  console.log(cat.toString());
};

ma​​mmal.js

"use strict";
class Mammal{
  constructor(name){
    this.name = name;
    this.kingdom = "mammalia";
  }
}

cat.js

"use strict";
class Cat extends Mammal{
  constructor(name){
    this.name = name;
    this.type = "Cat";
  }

  toString(){
    return this.type + " from kingdom " + this.kingdom + " has name " + this.name;
  }
}

起初,我以为我的 JSON 有问题,因为每个类都在一个单独的文件中,可能文件没有按正确的顺序加载。

ma​​nifest.json

{
  "manifest_version": 2,
  "name": "MyExtension",
  "description": "some tool",
  "version": "1.3.1",
  "permissions": [
    "storage",
    "tabs",
    "http://*/*",
    "https://*/*"
  ],
  "content_scripts": [
  {
    "matches": ["myWebsite"],
    "run_at": "document_end",
    "js": [
      "caseList/init.js",
      "caseList/mammal.js",
      "caseList/cat.js"
    ]
  }]
}

但是,经过大量调试和测试,没有任何效果! 唯一似乎“有效”的事情是如果我将class Cat extends Mammal 更改为class Cat

但既然猫是可爱的哺乳动物,我不想那样做!

问题:

  1. Chrome 扩展程序是否支持 ES6?
  2. 如何修复此代码,同时保留类继承和分隔文件?

【问题讨论】:

标签: javascript class google-chrome-extension ecmascript-6


【解决方案1】:

当然有,这就是没有语法错误的原因。

类构造函数中this is not defined 的唯一解释是没有正确执行继承,即构造函数错过了super(也解释了class Cat { ... } 工作的原因)。

应该是

class Cat extends Mammal{
  constructor(name){
    super(name);
    ...

【讨论】:

    猜你喜欢
    • 2015-12-07
    • 2017-09-06
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2012-02-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多