JS Practical Patterns

Abhishek Verma
Pragmatic Bytes
Published in
May 2, 2023
  1. Using Factory functions to create object
function watchlistFactory(name){

function createWatchlist(name){
this.name = name;
this.id = "wl_id_assoei02kdalik";
return { name,id }
}

return createWatchlist(name);

}


let newWatchlist = new watchlistFactory("testWL2")
/*
{
id: "wl_id_assoei02kdalik",
name: "testWL2"
}
*/

2. Using setter and getters

const person = {
firstName: "John",
lastName: "Doe",
language: "NO",
set lang(value) {
this.language = value;
},
set newProp(value) {
this.newProperty = value
}
};

person.lang = "english";
console.log(person.language)
person.newProp = "Property";
console.log(person.newProperty)

/*
"english"
"Property"
*/

--

--