问题
So I'm new to JavaScript, and have a project where I'm using the Node.js cookies module found here. I've been able to create cookies & set them correctly like so:
this.Vue.$cookies.set('cookieName', cookieValue, {
sameSite: 'lax',
secure: true
});
However, I want to create a wrapper function/class so I can set the sameSite: 'lax'
and secure: true
options as defaults, and not have to pass them in every time I call the set
function from that module. Obviously, I also want to be able to overwrite those options to something else if I want.
Looking through examples I've found elsewhere, I think the class should look something vaguely like this:
const cookies = require('cookie-universal-nuxt');
cookies(function ($) {
const defaultOptions = {
sameSite: 'lax',
secure: true
};
return {
get: function(name, options) {
return $.cookies(name, options)
},
set: function (name, value, options) {
$.cookies(name, value, // somehow options & defaultOptions are passed in and merged here)
},
};
});
However, this might be totally wrong. Like I said, I'm new to JS, so I'm pretty lost. Any help would be greatly appreciated!
回答1:
I don't think you need a class for this - a simple wrapper function will probably do what you need. Here's how to create a little factory function that creates a wrapper bound to a specific context:
function makeSetCookie($) {
return function(name, value, options) {
const defaultOptions = {
sameSite: 'lax',
secure: true
};
$.set(name, value, Object.assign(defaultOptions, options));
}
}
const setCookie = makeSetCookie(this.Vue /* or whatever */);
// and now you can use setCookie wherever
The caller can pass or not pass a value for the options
param. The line Object.assign(defaultOptions, options)
copies all keys/values from options
to defaultOptions
, overwriting any keys already in defaultOptions (sameSite, secure) if they appear in options
. If options
is null or undefined, that's fine - the value returned will just be defaultOptions
. More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
来源:https://stackoverflow.com/questions/60121161/how-to-create-a-wrapper-class-for-node-js-plugin