I want to do cookie.c.something = "hello". That will set the document.cookie to "something=hello;". Then I can get it back again with cookie.c.something. I have already made the get function, but I don't know how to do the set function. (when doing cookie.c.something = "hello" it calls the getter)
I thought this might work, then I realized that I can't get the property in the set function:
class cookie {
static get c() {
return this.object
}
/* What I want: */
static set c(setter) {
this.object["uses property 'hello'"] = setter
}
static get raw() {
return document.cookie;
}
static get object(){
let rem = {}
const cookies = cookie.raw.split(';').map(cookie => cookie.trim())
for (const cookieString of cookies) {
const [cookieName, cookieValue] = cookieString.split('=')
rem[`${decodeURIComponent(cookieName)}`] = decodeURIComponent(cookieValue)
}
return rem
}
}
I later found:
let myObj = {
id: 1,
name: 'tomato',
};
for(let fieldName of Object.keys(myObj)) {
console.log(`fieldName = ${fieldName}`);
Object.defineProperty(myObj, fieldName + "_property", {
set: function(value) {
this[fieldName] = value;
},
get: function() {
return this[fieldName];
}
});
}
myObj.id_property = 55; // setting id_property will set id
console.log(myObj.id); // so this will write 55
myObj.id = 123; // setting id
console.log(myObj.id_property); // this will write 123 because id_property returns id field
This almost would work, but it only will work for the once that I already have defined. I want it to work on all.
Working code: