为什么我的类构造函数中出现“Uncaught ReferenceError:this not not defined”?

时间:2017-01-31 17:00:46

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

背景

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

问题

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

即我在我的猫的构造函数中得到"use strict"; window.onload = function() { let cat = new Cat("Boby"); console.log(cat.toString()); }; 的错误!

init.js

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

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

cat.js

{
  "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"
    ]
  }]
}

起初,我认为我的JSON有问题,因为每个类都在一个单独的文件中,也许这些文件没有以正确的顺序加载。

的manifest.json

class Cat extends Mammal

然而,经过大量的调试和测试,没有任何作用! 唯一似乎“有效”的是我将class Cat更改为Sub Button4_Click() Dim CSVPath Dim thisWb As Workbook Dim wkb As Excel.Workbook Dim CSVUsed As Range Dim i As Integer Set thisWb = ActiveWorkbook Workbooks.Add ActiveWorkbook.SaveAs Filename:=thisWb.Path & "\new_workbook.xls" 'ActiveWorkbook.Close savechanges:=False Set FS = CreateObject("Scripting.FileSystemObject") CSVPath = ThisWorkbook.Path & "\CSV" If Not FS.FolderExists(CSVPath) Then MsgBox "CSV folder does not exist." Exit Sub End If Set thisWb = ActiveWorkbook For Each file In FS.GetFolder(CSVPath).Files If Right(file.Name, 3) = "csv" Then Set wkb = Application.Workbooks.Open(file.Path) Set CSVUsed = wkb.Sheets(1).UsedRange For i = 1 To CSVUsed.Rows.Count For j = 1 To CSVUsed.Columns.Count thisWb.Sheets(1).Cells(j, i).Value = CSVUsed.Cells(j, i).Value Next Next End If Next End Sub

但由于猫是可爱的哺乳动物,我不想这样做!

问题:

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

1 个答案:

答案 0 :(得分:1)

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

类构造函数中this is not defined的唯一解释是继承未正确执行,即构造函数未命中super(也解释了为什么class Cat { ... }有效)。

应该是

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