gpt4 book ai didi

javascript - 将函数设置为已弃用

转载 作者:行者123 更新时间:2023-12-03 15:25:59 24 4
gpt4 key购买 nike

几个月前,我创建了一个在 Npm 上发布的 Js 库。
现在我想重命名一些函数。
我读了this post我认为它非常有用。
假设我有一个文件 A :

export function function1(param1, param2) {
return param1 + param2
}
库用户可以使用的导出函数位于 index.js 文件中:
export { function1 } from './A'
我想将其重命名为 sum(param1, param2) .
我创建了这个 obsolete功能:
function obsolete(newFunction, oldFnName, newFnName) {
const wrapper = function () {
console.warn(
`Obsolete function called. Function '${oldFnName}' has been deprecated, please use the new '${newFnName}' function instead.`
)
newFunction.apply(this, arguments)
}
wrapper.prototype = newFunction.prototype
return wrapper
}
现在我该怎么办?
我想我必须以这种方式修改 A 文件:
/** @deprecated since version 2.0 */
export function function1(param1, param2) {
return sum(param1, param2)
}

export function sum(param1, param2) {
return param1 + param2
}
并添加 sum索引文件的功能:
export { function1, sum } from './A'
接着?如何使用 obsolete功能?

最佳答案

好的,所以您的评论似乎提示了这个问题(现在似乎已删除):

Suppose I have a function fun1 that I want to make it deprecated andthe new function is fun2. How can I use this obsolete function? Itseems interesting


来自 this question .

所以首先,你得到一个 JSdoc ( /** @deprecated since version 2.0 */ ) 注释和这个函数混淆了。

JSDoc is a markup language used to annotate JavaScript source code files


source
因此,这仅在您计划创建 JSdoc 注释时才有用。我假设你不是。如果您使用 JSdoc,那么这应该可以按原样工作吗?

所以忽略了我要回到你的问题 this code .
查看您可以使用它的代码(不是 100% 确定,因为我没有编写它):

// the function from the previous question
function obsolete(oldFunc, newFunc) {
const wrapper = function() {
console.warn(`WARNING! Obsolete function called. Function ${oldFunc.name} has been deprecated, please use the new ${newFunc.name} function instead!`)
newFunc.apply(this, arguments)
}
wrapper.prototype = newFunc.prototype
return wrapper
}

// this is the function that is the replacement for obsfunc
function newfunc(){
console.log('new called');
}

// this is the function that is being made "obsolete"
function obsfunc(p) {
return obsolete(obsfunc, newfunc)();
}


// when you call the obsolete function it's actually the new function
// that gets triggered and an error is displayed in the console.
obsfunc();

in my case functions have parameters and a return value


此代码不支持。在 Js 规范中没有“废弃”函数的官方方法。 TBH this is the correct (now deleted) answer这个问题IMO。因此,您需要编写自己的解决方案。也不清楚您对“过时”的定义是什么? Decorators is a good option

关于javascript - 将函数设置为已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64738751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com