0

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.

  • Whether you call `Repo` with or without `new` only changes the value of `this` in the `this.repository = …;` part. What `this` refers to inside the `repository` function depends *only* on how that function is called, and that's the same in both your examples - as a method of the `Repository` object. – Bergi Aug 21 '17 at 03:24
  • Hint: if you just export the object anyway, you shouldn't even need that `Repo` function (regardless whether with or without `new`). Just assign that object literal directly to `module.exports` - or even assign the method to `exports.repository`. – Bergi Aug 21 '17 at 03:26
  • Thanks for the explanation. I will try to implement the hint you mentioned. – LifeStartsAtHelloWorld Aug 21 '17 at 03:36

0 Answers0