假设一个库具有如下函数:
class Stuff {
total () {
return 4; // might be some calculation
}
}
Run Code Online (Sandbox Code Playgroud)
但是你想要更新它以使用getter,例如:
class Stuff {
get total () {
return 4;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法以向后兼容的方式进行这样的更改?那么使用库假定函数的代码不会中断?
stuff.total // should work with new version
stuff.total() // hopefully this still works
Run Code Online (Sandbox Code Playgroud)
编辑:这个问题更多的是关于图书馆的演变(更一般).另一个是关于特定的解决方案,从呼叫站点的角度来看.
你不应该这样做.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}` );Run Code Online (Sandbox Code Playgroud)
但有一些警告.stuff.total这里是一个吸气剂,它返回一个函数,而不是一个数字.在预期基元的任何地方使用该函数会导致函数被调用并且它的返回值被替代使用,但它仍然是一个函数.当您登录stuff.total.toString( )或时,这是显而易见的typeof stuff.total.
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |