Home > Software design >  Set value of a js file properties from outside of it
Set value of a js file properties from outside of it

Time:02-25

I`m new to JS and apologize for asking a primary question! We have this first.js file as a js class example with:

const {MakeRequest} = require("./Request");

let api;
let token;
let unique_token;

function chat(data, unique_token = null) {
    try {
        if (api != null && token != null) {
            return MakeRequest(token, api, data, unique_token)
        } else {
            return {
                "provider": {
                    "website": "https://example.com",
                    "source": "Example"
                },
                "status": true,
                "response": [],
                "options": {},
                "error": {
                    "code": 207,
                    "message": "Token or Api token did not valueted!"
                }
            }
        }
    } catch (e) {
        return {
            "provider": {
                "website": "https://example.com",
                "source": "Example"
            },
            "status": true,
            "response": [],
            "options": {},
            "error": {
                "code": e.code,
                "message": e.message
            }
        }
    }
}

module.exports = {
    token,api,unique_token,chat
}

also, I have this second.js file as a executable js file:

const object = require("./first.js")

object.token ="123456"
object.api ="123456"
object.token ="123456"
console.log(object.chat("hello"))

If I run the second.js file, the api variable is undefined and didn`t get the value from second.js, how can I resolve this problem without change the second.js codes!

CodePudding user response:

You can't edit a variable from a scope outside where it was declared.

Consider passing the values as arguments to chat function when you call it.

CodePudding user response:

You might want to consider classes for this . made an example of that , you can find it live on https://www.typescriptlang.org/play?filetype=js#code/PTAEDMEsCcGcBcB0ArWoCmAPAhgWwA4A26AUKOaAMaHaxoCSAduAPYDeZF5lLjC0AV0rwW0ABTZ8kADQiA1ukbSBjSAEcB6APrzFASg5cu8ABaRYiSZFABeUFc5HQp84l2NbzlgsaOjLixV1TR1vRU8gjW13P3IAX1iqE2x4MQATFOwDRO5k1JyKAMspaQLyIvdSp2MzQNUo0J8q6vIM GwCvUSErh6KEHsPLDwidFAWcCSUiBVhSF4-cFn4eY9KPIkSysiQyraswxaqXgR7QkJPQ6P7LbClHei76X2y0D6Wnj4WYkRCFgBzMQAIgAEtZpM48mcLvtQOZQEDpNhzl1eiQBrB0J80ig0MMCMQSH5Pqd3LYgQBGABMAGYACwAVgAbEDiSd4DdrDZKbTGSy2XwOQ9GuE7Dz6cygeQBgB3FLrSHwwiQRhjFWgACeLAE0GOaXQAEJQBD6KAAEboZXoABuYy1AlAuHQ2EYHJYZuQWKQwpifmIHJVrE8qploCYrDEiUqiSszS4Prufi6fkDLEQ6xSwIAgqBYJACWN9kC9EA

CodePudding user response:

I think you can go on Stackoverflow to fing an example

  • Related