By user614946

2018-06-13 14:08:28 8 Comments

Hi I am trying to access a private variable from a implementation pattern.

 var d = (function(){
  var jsData;

  function init(){

  function _bind(){

  function _initilise(){
    jsData = `data data`;
    console.log('..in_initilise..' + jsData);

  return {
    init : init,
    jsData : jsData
  $(document).ready ( function(){
<script src=""></script>

The output: console.log('..in_initilise..' + jsData); : data. The output: console.log(d.jsData); is always 'undefined'

The last one is confusion as I am setting value in _initilise() then why it is undefined?


@Mikael Lennholm 2018-06-13 14:25:48

The property jsData in the object you return isn't a pointer to the local variable jsData, it's a copy of the value that the local variable had at the time you created and returned the object, which was undefined. If you want read-only access to the local variable you can define a getter for it that returns its value, like this:

var retObj = {
  init : init

Object.defineProperty(retObj, 'jsData', {
  configurable: false,
  get: function() { return jsData; }

return retObj;

@RIYAJ KHAN 2018-06-13 14:21:10

var jsData; It declared as primitive value.

When IIFE is called,it return jsData value defined during initialisation. i.e. undefined.

Now,even you are updating value,its not updating the returned copy of jsData.

So,it remain undefined

Solution :

Defined getter to get the value of jsData inside closure instead returning it directly .

 function getData(){


return {
    init : init,
    getData : getData




Define jsData as an object with value as property and update value property.

Because of reference ,you always have updated copy.

  var jsData={
    value : null


function _initilise(){
    jsData.value = 'data data';
    console.log('..in_initilise..' , jsData.value);

@user614946 2018-06-13 14:23:41

Bravo, that was excellently the thing missing, I made the change and it worked!

Related Questions

Sponsored Content

88 Answered Questions

[SOLVED] How do JavaScript closures work?

60 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

52 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

34 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

64 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 4701013 View
  • 5920 Score
  • 64 Answer
  • Tags:   javascript arrays

49 Answered Questions

[SOLVED] Create GUID / UUID in JavaScript?

  • 2008-09-19 20:01:00
  • Jason Cohen
  • 1222739 View
  • 3149 Score
  • 49 Answer
  • Tags:   javascript guid uuid

24 Answered Questions

[SOLVED] For-each over an array in JavaScript?

26 Answered Questions

49 Answered Questions

Sponsored Content