Home > Mobile >  Use object passed into function without changing the object
Use object passed into function without changing the object

Time:09-29

How can I pass object passed into function without changing even if the passed object is has changed.

let theObj = {
    parameter: '11'
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function myFunc(myObj) {
    await sleep(5000)
    console.log(myObj.parameter)
}

myFunc(theObj)
theObj.parameter = '22'

output:

> 22

How can I get 11 as the output, the value of theObj.parameter when the function was called ?

I don't want to deep clone because of speed.

CodePudding user response:

Use spread operator

let theObj = {
    parameter: '11'
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function myFunc(myObj) {
    await sleep(5000)
    console.log(myObj.parameter)
}

myFunc({...theObj})
theObj.parameter = '22'

CodePudding user response:

Objects are passed by reference, so you need to pass a copy of the object to your myFunc function.

There are multiple approaches to copying an object, but for your case this would work:

myFunc({...theObj})
theObj.parameter = '22'

CodePudding user response:

Instead of copying, you can save the value before the await.

let theObj = {
    parameter: {example: '12'},
    parameter2: 2
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function myFunc(myObj) {
    let parameter = myObj.parameter
    let parameter2 = myObj.parameter2
    
    await sleep(5000)
    console.log(parameter, parameter2)
}

myFunc(theObj)
theObj.parameter = '22'

  • Related