You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript自定义Matrix类调用cof实例方法报undefined错误求解

报错原因解析

你的问题本质是普通函数的this指向丢失,具体逻辑如下:

  • 你在det方法内部定义的recursiveDeterminantMatrix是普通函数,类内部默认启用严格模式,普通函数直接调用时的this指向为undefined,而非当前Matrix类的实例。因此你在函数内部调用this.cof()时,相当于从undefined上读取cof属性,就抛出了Cannot read property 'cof' of undefined的类型错误。
  • 你在det内部定义普通cof函数时运行正常,是因为这种场景下不需要通过this调用cof,直接使用的是det方法作用域内的局部函数,不存在this指向问题。
修复方案

可选修复方式(任选其一即可)

  • 方式1:将递归函数改为箭头函数,箭头函数会继承外层det方法的this指向(det作为实例方法的this本身指向当前Matrix实例),就能拿到正确的cof方法:
    把function recursiveDeterminantMatrix(matrix) {修改为const recursiveDeterminantMatrix = (matrix) => {即可。
  • 方式2:在det方法开头提前缓存实例指向:
    在det方法内部第一行添加const self = this,递归调用cof时改为self.cof(matrix, 0, i)即可。

额外bug修复

你现有的cof方法还存在参数错误:cofMat.splice(cofMat[i],1)的第一个参数需要传入要删除的行索引i,而非cofMat[i]这个数组元素,正确写法为cofMat.splice(i,1),否则删除行的逻辑会失效。

修复后完整代码
class Matrix{
  constructor(matrix){
    this.matrix = matrix
  }   
 
  cof(matrix = this.matrix, i, j) {
    let cofMat = matrix.map(row =>
      row.filter((_, colIndex) => j !== colIndex)
    )
    // 修复splice参数错误
    cofMat.splice(i,1)
    return cofMat
  }
     
  det(matrix = this.matrix) {
    let validInput = true;

    // input validation
    let columnLength = matrix.length;
    matrix.forEach((row) =>
      row.length === columnLength ? (validInput = true) : (validInput = false)
    );
    if (!validInput) return "Input a valid n*n matrix";

    // 改为箭头函数继承this
    const recursiveDeterminantMatrix = (matrix) => {
      if (matrix.length === 2 && matrix[0].length === 2) {
        let result = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
        return result;
      } else {
        let answer = 0;
        for(let i =0; i< matrix.length; i++) {
          let cofactor =
            (-1) ** i *
            matrix[0][i] *
            recursiveDeterminantMatrix(this.cof(matrix, 0, i));
          answer += cofactor;
        };
        return answer;
      }
    }

    return recursiveDeterminantMatrix(matrix);
  }  
}

let matrix = [[1,2,3],[4,5,6],[7,8,8]];
let mat = new Matrix(matrix).det()
console.log(mat) // 输出正确结果3

内容的提问来源于stack exchange,提问作者sadat-saim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:09:03