如何解决JS-值过时引用和值之间的转换
我想知道javascript中的引用在传递给函数时何时转换为值(在所有情况下)。
对于同步执行,似乎在您不提供整个对象(myObj.value
)并转至更深的层次(将still a reference
传递到另一个函数)后立即进行转换,则引用得到转换为值。
对于异步执行,除非您传递完整对象,否则它似乎会立即转换。到目前为止,我一直通过将完整的对象和路径传递给我感兴趣的属性来保留引用行为。
关于js,还有更多“怪异”的引用/值转换吗? 我可能无法标记某些内容以始终作为参考。 是否使用“更细”(其他)模式来保持参考行为?
(async () => {
const myArr = [];
const sleep = (timeout) => new Promise(res => setTimeout(res,timeout));
const myObj = {
timedOut: false
}
const asyncLogger = async param => (await sleep(500),param);
const asnycWrapper = async param => (await sleep(500),asyncLogger(!param.timedOut));
const interval = setInterval(() => {
myObj.timedOut = !myObj.timedOut
},100);
console.log("== Not working Async/ Await ==\n\n")
for (let i = 0; i < 3; i++) {
console.log(`This is the iteration ${i}`)
await sleep(100);
console.log(`asnycWrapper Output : ${await asnycWrapper(myObj)}`);
console.log(`asyncLogger Output : ${await asyncLogger(!myObj.timedOut)}`);
console.log('\n')
}
const logger = async param => param;
const wrapper = async param => logger(!param.timedOut);
console.log("== Working Synchronous ==\n\n")
for (let i = 0; i < 3; i++) {
console.log(`This is the iteration ${i}`)
await sleep(100);
console.log(`Wrapper Output : ${await wrapper(myObj)}`);
console.log(`Logger Output : ${await logger(!myObj.timedOut)}`);
console.log('\n')
}
const newAsyncWrapper = async (ptr,path) => (await sleep(500),ptr[path]);
const newAsyncLogger = async param => (await sleep(500),param);
console.log("== Working Asynchronous ==\n\n")
for (let i = 0; i < 3; i++) {
console.log(`This is the iteration ${i}`)
await sleep(100);
console.log(`newAsyncWrapper Output : ${await newAsyncWrapper(myObj,"timedOut")}`);
console.log(`newAsyncLogger Output : ${await newAsyncLogger(!myObj.timedOut)}`);
console.log('\n')
}
})()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。