I was watching a course and its instructor implemented the prototype members
outside the constructor function
and when you do such a thing, It causes multiple problems. I was wondering, can I declare these prototype members
inside the constructor function
, because in that case It works properly?
(I looked up in various websites and they had declared the prototype members
outside the constructor function
and by the way I know these kind of optimization is premature and useless but It's just an exercise)
prototype members outside the constructor function:
function Stopwatch(){
let running,stop,start;
}
Stopwatch.prototype.start=function(){
if(running) throw new Error("This watch is already started! ");
start=console.time("time")/1000;
running=true;
}
Stopwatch.prototype.stop=function(){
if(!running) throw new Error("The watch hasn't started yet!");
stop=console.timeEnd("time")/1000;
running=false;
}
const timer=new Stopwatch();
prototype members inside the constructor function:
function Stopwatch(){
let running,stop,start;
Stopwatch.prototype.start=function(){
if(running) throw new Error("This watch is already started! ");
start=console.time("time")/1000;
running=true;
}
Stopwatch.prototype.stop=function(){
if(!running) throw new Error("The watch hasn't started yet!");
stop=console.timeEnd("time")/1000;
running=false;
}
}
const timer=new Stopwatch();