gpt4 book ai didi

javascript - 在JavaScript中通过bind传递 'this'时如何更改它的顺序?

转载 作者:行者123 更新时间:2023-11-28 17:48:47 25 4
gpt4 key购买 nike

我有以下代码可以说明我的问题。

var p = Promise.resolve('this-is-the-title');
createFilePath=(title, ex)=>{
let ready = `${title.split(' ').join('-')}.${ex}`
console.log(ready)
return Promise.resolve(ready)
}
makeFile=(path,content)=>{
return{
file: path,
content
}
}
p
.then(createFilePath.bind(this,'md'))

将记录的是md.this-is-the-title。有没有办法改变 this 的顺序(类似于 .then(createFilePath.bind('md', this)))

createFilePath 被其他函数使用,因此我不想浏览代码并更改 createFilePath(ex,title)

最佳答案

目前您对 bind 的使用相当于:

p.then(function(promiseValue) {
return createFilePath.call(this, 'md', promiseValue)
})

这里的promiseValue是promisep的值,在你的例子中是'this-is-the-title'bind 用于“部分应用”函数 createFilePath 的参数,但您只能从左到右执行此操作,不能跳过第一个参数并只指定第二个参数。您可以使用包装函数自己完成:

p.then(function(promiseValue) {
return createFilePath.call(this, promiseValue, 'md')
})

如果您不需要 createFilePath 中的 this 值(在示例中不需要,但在实际代码中可能不需要),那么您可以简化此操作进一步:

p.then(function(promiseValue) {
return createFilePath(promiseValue, 'md')
})

关于javascript - 在JavaScript中通过bind传递 'this'时如何更改它的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46129430/

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