拆散一个大班的巧妙方法

Eloquent way to break apart a big class

本文关键字:大班 方法 一个      更新时间:2023-09-26

我有一个包含很多方法的类。即使在重构&取出不使用this上下文的块,每个方法仍然只有几百行:

class BigFella {
  constructor() {
    // lots of stuff
  }
  bigMethod1() {
    // 300 LOCs
  }
  bigMethod2() {
    // 300 LOCs
  }
}

给每个方法都提供自己的文件是很好的,但我能想到的唯一方法是:

import classMethod1 from './classMethod1';
class BigFella {
  constructor() {
    // lots of stuff
  }
  bigMethod1(a,b) {
    return classMethod1.call(this, a,b);
  }
}

这是最好的模式吗?使用call会对性能产生影响吗?我应该接受它吗;是否有2000+LOC文件?

在node.js中,您可以混合ES6和prototype的形式:

想象一下class1.js文件:

"use strict";
class BigFella {
  constructor() {
    console.log('cons');
  }
  bigMethod1() {
    console.log('big1');
  }
  main() {
    this.bigMethod1();
    this.bigMethod2();
  }
}
module.exports = BigFella;

在class1b.js文件中扩展:

"use strict";
// import BigFella from './class1.js'; Does not works in nodejs
var BigFella = require('./class1.js');
BigFella.prototype.bigMethod2 = function() {
  console.log('big2');
}
var b=new BigFella();
b.main();