简体   繁体   中英

adding properties and methods to object in different js file

I am creating a config.js file having say an object known as contextTokenObject

//This holds context information or the information which will be transferred at various places of the app 

let contextToken = {}

module.exports = {
    contextToken
}

Now, I want to add property and methods to that context object from another file (when I am creating my passport stratergy)

Instead of pasting entire code, consider passport.js file In this passport.js file,

I am importing context Token object in this file.

const contextObject = require("./config.js") 

Now, say, I want to add following property to my above object

let TokenToStore = { "googleRefreshToken": refreshToken, "`googleAccessToken": accessToken, "expires_in": params.expires_in}`   

Question: How can I do it?

Update: what I have tried. Like mentioned above, I have created an object and I am importing it in my passport strategy

const contextObject = require("./../config/context.js")

then in the passport callback I am doing something like this

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL:  process.env.GOOGLE_CALLBACK_URL,
    userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
    accessType: 'offline'
  }, (accessToken, refreshToken, params, profile, cb) => { 
        //Sorting the data we recieve and removing unwanted stuff 
        let profileSort = authHelper.extractGmailProfile(profile)
        //Update refresh token whenever recieved
        let TokenToStore = { "googleRefreshToken": refreshToken, "googleAccessToken": accessToken, "expires_in": params.expires_in}    
        //Context object 
        contextObject.contextToken["googleToken"] = TokenToStore

This is throwing following error

Cannot set property 'googleToken' of undefined

Any help would be appreciated.

You do have several ways for doing it.

The first one in node.js will be to export/define that object as global. In that way, you don't even need anymore to import it in the different files. I am going to tell you immediately that this solution, even if it works, and that's pretty a straight forward, it's not my preferred one. Global variables are evil in any case .

Then of course, it can depend on the case, but usually it is not the best practice to use. That's really error prone and delicated. A new module can easily override your global variable for example.

By the way, you can do that as following:

global.contextObject = { ... };

And then you can use it straight forward inside your files. So if you want to add props in another file, you can do directly something like:

contextObject.TokenToStore = {
  "googleRefreshToken": refreshToken, 
  "googleAccessToken": accessToken, 
  "expires_in": params.expires_in
};

Another way to do it, is to use the prototype , but you have to slightly change your syntax when defining the obj in order to use a function constructor, otherwise using the prototype for adding props through an object literal will result in assigning the new props to all the objects, as you can see below:

 const obj = { firstProp: 'I am a first prop' }; console.log(obj); Object.getPrototypeOf(obj).secondProp = 'I am a second prop'; console.log(obj); const obj2 = { test: 'I am a test' }; console.log(obj2);

So the correct way to do it, will be:

 const obj = new function () { this.firstProp = 'I am a first prop'; return this; }; console.log(obj); // then export your obj // In the other file import back your obj and add things to the prototype Object.getPrototypeOf(obj).secondProp = 'I am a second prop'; console.log(obj); const obj2 = { test: 'I am a test' }; console.log(obj2);

The last way to do it is simply adding plain props to the object, or even better, in these cases when you want to add props to a cusotm object in a lot of places, use Object.defineProperty for defining them, which gives you a lot of more options for the new props.

For example you may want that the new props that you assign in the new object can't be changed in some other file, whcih is impossible adding the props with literal syntax.

An example is below:

 const obj = { firstProp: 'I am a first prop' }; console.log(obj); // then export it // import it somewhere else obj.secondProp = 'I am a second prop'; console.log(obj); // or assign it with defineProperty Object.defineProperty(obj, 'secondProp', { value: 'I am a not changable second prop', writable: false }); console.log(obj); // the following will be ignored obj.secondProp = 'new value'; console.log(obj);

What's the best way to take? That really depends on your use case.

I would avoid global variables, and I would avoid literals, so my choice would be to use prototypes and specially use defineProperty for new props in these cases. But that's really up to you. All of them achieve what you are looking for.

contextObject.googleRefreshToken = refreshToken , and so on,
or
newContextObject = Object.assign(contextObject, refreshToken);

or es6 way

newContextObject = { ...contextObject, ...refreshToken }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM