Home > OS >  How I can change value varible in a file in another file in javascript
How I can change value varible in a file in another file in javascript

Time:09-24

I want to change value variable in an index.js in another file, but i can't do that and this is my code example

index.js

   var length = 0;
   client.commands.get('join').excute(length);

anotherfile.js

module.exports = {
    name: 'join',
    description: "",
    excute(length){
       length  ;
    }

length in index.js is 1 = 2, but length in anotherfile.js is not

I imported anotherfile.js to index.js

So how i can change value in length variable

Thank you so much and sorry for my bad english

CodePudding user response:

It's not working because JavaScript doesn't pass variables with primitive data types, such as an integer, through its reference to other functions, but rather creates a whole new variable with a different memory address. The only way you can mutate the original memory location is if you're passing in an array or object, which JavaScript will then pass in a pointer to the original memory location, ie "reference", to the function.

So you'd have to change the datatype of length to an object, and add the value/length of the object as a property. The excute function would then just access that property and increment it like so:

index.js:

const obj = { length: 0 }

client.commands.get('join').excute(obj);

anotherFile.js:

module.exports = {
    name: 'join',
    description: "",
    excute(obj){
       obj.length  ;
    }
}

Keep in mind, you have to pass the whole object, otherwise if you just pass the obj.length, it will simply copy the value and create a whole new variable set to that value.

  • Related