I am new to Javascript and I have a background in Java. I am trying our different ways to create/export/use functions (calling it in a simple way and using new operator). I was exploring and trying different ways, however, when I wrote the following code, I was expecting different results (may be). But I found that there was no difference.
Using new keyword
var Repo = function() {
this.repository = function(type) {
if(type === 'task') {
if(this.Task) {
console.log("Rturned saved cache task");
return this.Task;
}
this.Task = require("./taskrepository")('jdbc');
return this.Task;
}else if(type === 'user') {
this.user = require("./user");
return this.user;
}
}
module.exports = new Repo()
I was expecting the object Task to be returned from cache when called a second time, which worked fine.
Using just the function call
var Repo = function() {
return {
repository : function(type) {
if(type === 'task') {
if(this.Task) {
console.log("Rturned saved cache task");
return this.Task;
}else {
this.Task = require("./taskrepository")('jdbc');
return this.Task;
}
}else if(type === 'user') {
this.user = require("./user");
this.user;
}
}
}
}
module.exports = Repo()
This produces the same result.
I assumed using new keyword creates an instance where all the variables are stored, so when called second time, it will retrieve from the cache and when I call the function(), it will new instance of Task everytime.
Does this keyword here works the same way when called using new?
Main.js
'use strict';
var Task = require("./task");
var Repository = require("./repositorypattern");
var task1 = new Task(Repository.repository('task').get(1));
task1.completed();
task1.saved();
var task2 = new Task(Repository.repository('task').get(2));
task2.completed();
task2.saved();
var task3 = new Task(Repository.repository('task').get(3));
task3.completed();
task3.saved();
I am having a hard time to wrap my head around functions in javascript.