如果回傳物件,是否可以阻止函式執行?
function number(a) {
console.log(a)
return {
add: b => console.log(a b)
}
}
number(6).add(4)
這將列印6然后10. 我正在尋找的行為是僅10在.add()被呼叫時列印,但6在.add()未呼叫時列印。.add()發生后應該以某種方式停止number()執行(什么?)。我從來沒有在javascript中看到過這樣的事情,所以我幾乎可以肯定這是不可能的,但也許我錯過了一些東西?
編輯
根據要求,我將包括一個更現實的例子。注意:這只是對好的語法的研究,我知道如何用不同的語法來實作功能。
function update(obj, props) {
for (const p in props) {
obj[p] = props[p]
}
return {
if(condition) {
for (const p in condition) {
if (obj[p] === condition[p]) {
obj[p] = props[p]
}
}
}
}
}
const obj1 = {z: 0, h: 0}
const obj2 = {a: 0, b: 'hi'}
update(obj1, {z: 10, h: 10}) // Will update the object regardless.
update(obj2, {a: 100, b: 'hello'}).if({a: 'x', b: 'y'}) // This would not update the object, because the condition is not met. (But it does)
console.log(obj1)
console.log(obj2)
uj5u.com熱心網友回復:
[它] 應該在它發生后以某種方式停止 [...] 執行(什么?)。
這是不可能的。方法既不if能改變過去,也不能update預測將來是否.if()會呼叫它的回傳值。之后你能做的最好的事情就是撤銷之前所做的,但這很丑陋。
相反,將您的語法從
update(obj2, {a: 100, b: 'hello'}).if({a: 'x', b: 'y'});
類似于
when({a: 'x', b: 'y'}).update(obj2, {a: 100, b: 'hello'})
或者(如果你只想引入一個變數update)比如
update.if({a: 'x', b: 'y'}).then(obj2, {a: 100, b: 'hello'})
uj5u.com熱心網友回復:
只是不要console.log()來自任何一個功能。回傳值并在console.log()外面做。
console.log(
number(6).add(4)
);
如果您要設計這樣的鏈接 API,請注意不要產生奇怪的副作用。讓每個函式做一件不同的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532727.html
標籤:javascript功能
上一篇:std::invoke_result<F,Args...>似乎沒有給出const型別
下一篇:強制python函式引數沒有順序
