javascript - 是否有向后兼容的方式来更新库以使用 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
编辑:这个问题更多的是关于图书馆的演变(更笼统)。另一个是关于一个特定的解决方案,从呼叫站点的角度来看。
解决方案
你不应该这样做。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
。
推荐阅读
- python - 使用列上的过滤器进行数据操作
- c# - [BotFramework]:在 C# 中使用 SDK V4 开发的 BOT 中,有没有办法在英雄卡或自适应卡中显示 Oauth 提示?
- python - How to see lots of spots on a graph clearly?
- windows-10 - Conda-forge spaCy 安装失败 - 错误:WinError 87 - 参数不正确
- python - 使用python绘制具有大量异常值的每个类别的数据框值的更好方法
- php - 如何访问此 API 返回的值
- cassandra - 在 ubuntu 14.04 上安装 cassandra 时出错
- asp.net-core - .NET Core 2.2 发布问题
- python - 根据列表向字符串添加空格
- django - 为格式化的用户输入定制 Django Crispy 表单(由用户格式化)