1

Let's say that i have this code:

module.exports = {
   head: {
     title: "Some title"
   }
}

Can i get access to this head object inside module.export i.e.

module.exports = {
   head: {
     title: "Some title"
   },
   test: function() {
     return this.head.title
   }
}

Thx for help.

Lukas
  • 7,384
  • 20
  • 72
  • 127

1 Answers1

1

You can use Bind outside of the function to maintain reference.

var module = {};
module.exports = {
  head: {
    title: "Some title"
  },
  test: function() {
    return this.head.title
  }
}

var title = module.exports.test.bind(module.exports);
console.log(title());

or you can use apply inside the function to maintain reference.

var module = {};
module.exports = {
  head: {
    title: "Some title"
  },
  test: function() {
    return hit.apply(module.exports.head)

    function hit() {
      return this.title;
    }
  }
}

console.log(module.exports.test());

And if you want to chang the title you can use a class.

var module = {};
class Update {
  constructor(a, b) {
    this.module = a;
    this.string = b;
  }
  get titles() {
    return this.module.exports = {
      head: {
        title: this.string || "I'm sooo defualt"
      },
      test: function() {
        return hit.apply(module.exports.head)

        function hit() {
          return this.title;
        }
      }
    }
  }
}


const newString = new Update(module, 'no way brah');
const allTheWay = new Update(module, 'all the way brah');
console.log(newString.titles.test());
console.log(allTheWay.titles.test());
const defaults = new Update(module);
console.log(defaults.titles.test());
console.log('I am with the last guy,', module.exports.test());

And if you have no class.

var module = {};
module.exports = {
  head: {
    title: "Some title"
  },
  test: function() {
    return hit.apply(module.exports.head)

    function hit() {
      return this.title;
    }
  }
}

module.exports.head.title= 'hello world';

console.log(module.exports.test());
 
Rick
  • 1,035
  • 10
  • 18
  • So, how can i set a new value for title, is it possible? – Lukas Jun 28 '17 at 20:18
  • 1
    @lukas yes it is possible, will update answer when I get a change – Rick Jun 28 '17 at 20:39
  • i can't use a class ... :( i have to do this inside this module without any external actions – Lukas Jun 28 '17 at 23:16
  • 1
    @Lukas can you select and upvote the answer if you found it helpful – Rick Jun 28 '17 at 23:51
  • can i do this inside this module? right now i'm doing this globally but if i have loop inside this test object i wish to have unique value for title... – Lukas Jun 29 '17 at 09:59
  • 1
    Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/147965/discussion-between-arrow-and-lukas). – Rick Jun 29 '17 at 16:52