首页 > 解决方案 > 是否有向后兼容的方式来更新库以使用 getter?

问题描述

假设一个库具有如下功能:

class Stuff {
  total () {
    return 4; // might be some calculation
  }
}

但是您想更新它以使用 getter,例如:

class Stuff {
  get total () {
    return 4;
  }
}

有没有办法以向后兼容的方式进行这样的更改?那么假设函数不会中断的使用库的代码呢?

stuff.total   // should work with new version
stuff.total() // hopefully this still works

编辑:这个问题更多的是关于图书馆的演变(更笼统)。另一个是关于一个特定的解决方案,从呼叫站点的角度来看。

标签: javascript

解决方案


你不应该这样做。stuff.total应该是数字或函数,但不能同时是两者。这将使将来的代码非常混乱且难以维护。

也就是说,您可以按照您想要的方式做一些事情:

class Stuff {
  get total () {
    const callable = function ( ) {
      return 4;
    };
    callable[Symbol.toPrimitive] = callable;
    return callable;
  }
}

const stuff = new Stuff;
console.log( stuff.total );
console.log( stuff.total( ) );
console.log( 1 + stuff.total );
console.log( 1 + stuff.total( ) );

// stuff.total is a function, not a number!
console.log( typeof stuff.total );
console.log( stuff.total.toString( ) );

// But if it's implicitly coerced to a string, it's toString is not called:
console.log( '' + stuff.total);
console.log( `${stuff.total}` );

不过有一些警告。stuff.total是一个 getter,它返回一个函数,而不是一个数字。在预期原语的任何地方使用该函数会导致调用该函数并使用它的返回值,但它仍然是一个函数。当您登录stuff.total.toString( )或时,这一点很明显typeof stuff.total


推荐阅读