Reputation: 2474
I have method like below
function setme(){
var date = 'new date()';
}
function getName1(){
setme();
}
function getName2(){
setme();
}
function getName3(){
setme();
}
function getName4(){
setme();
}
how do avoid calling setme method every time, do we have any other optimized solution ?
Upvotes: 0
Views: 169
Reputation: 71
This will only set date once and then set the setFunction to null to release the memory if your setFunction is very large for some reason.
function executeOnce(executable) {
return function () {
if (executable !== null) {
executable();
executable = null;
}
}
}
var setme = executeOnce(
function() {
date = 'new date()';
}
);
function getName1(){
setme();
}
function getName2(){
setme();
}
function getName3(){
setme();
}
function getName4(){
setme();
}
Upvotes: 1
Reputation: 1995
I'm not sure exactly what you are trying to accomplish since a date will always need a function to retrieve the latest. But if what you want is to define variables in the constructor in a class oriented way:
class Names {
constructor() {
this.date = new Date();
}
getName1() {
return this.date;
}
getName2() {
return this.date;
}
getName3() {
return this.date;
}
}
//If you only create a new class object
var n = new Names;
console.log(n.getName1());
console.log(n.getName2());
console.log(n.getName3());
//if you create a new class object for every call
console.log((new Names).getName1());
console.log((new Names).getName2());
console.log((new Names).getName3());
Upvotes: 3