背景
我正在制作一个 Chrome 扩展程序,可以在页面重新加载后打印日志。我将所有功能都放在一个错误页面中,所以最近我决定使我的代码可读并使用 classes 重构它。 .
问题
我设法让我的扩展启动并运行,但现在,每次加载页面时,都会出现很多错误。
即,我收到错误 Uncaught ReferenceError: this is not defined
在我的猫的构造函数中!
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;
}
}
起初,我以为我的 JSON 有问题,因为每个类都在一个单独的文件中,也许这些文件没有按正确的顺序加载。
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"
]
}]
}
然而,经过多次调试和测试,没有任何效果!
唯一似乎“有效”的是我是否改变 class Cat extends Mammal
至class Cat
.
但是由于猫是可爱的哺乳动物,我不想这样做!
问题:
- Chrome 扩展程序支持 ES6 吗?
- 如何修复此代码,同时保留类继承和分隔文件?
最佳答案
当然,他们这样做,这就是为什么没有语法错误。
在类构造函数中 this is not Define
的唯一解释是继承没有正确执行,即构造函数错过了 super
(也解释了为什么 class猫 { ... }
有效)。
应该是
class Cat extends Mammal{
constructor(name){
super(name);
...
关于javascript - 为什么我的类构造函数中出现 "Uncaught ReferenceError: this is not defined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41963271/