0

Background

I am making a Chrome extension that prints a log once a page reloads. I have all my functions in one bug page, and so lately I decided to make my code readable and refactor it using classes.

Problem

I managed to get my extension up and running, but now, every time I load the page, a get a lot of errors.

Namely, I get the error of Uncaught ReferenceError: this is not defined in my cat's constructor!

init.js:

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

mammal.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;
  }
}

At first, I thought I had a problem with my JSON, since each class is in a separate file, perhaps the files were not being loaded in the correct order.

manifest.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"
    ]
  }]
}

However, after much debugging and testing, nothing works! The only thing that seems to 'work' is if I change class Cat extends Mammal to class Cat.

But since cats are lovely mammals, I don't want to do that!

Questions:

  1. Do Chrome extensions support ES6?
  2. How can I fix this code, while keeping class inheritance and separated files?
Makyen
  • 31,849
  • 12
  • 86
  • 121
Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266

1 Answers1

1

Of course, they do, that's why there is no syntax error.

The only explanation for this is not defined in class constructor is that inheritance wasn't performed correctly, i.e. the constructor misses super (also explains why class Cat { ... } works).

It should be

class Cat extends Mammal{
  constructor(name){
    super(name);
    ...
Estus Flask
  • 206,104
  • 70
  • 425
  • 565