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?


@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

48 Answered Questions

76 Answered Questions

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

  • 2011-04-23 22:17:18
  • Walker
  • 5490013 View
  • 6813 Score
  • 76 Answer
  • Tags:   javascript arrays

65 Answered Questions

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

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

31 Answered Questions

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

52 Answered Questions

[SOLVED] Create GUID / UUID in JavaScript?

  • 2008-09-19 20:01:00
  • Jason Cohen
  • 1404519 View
  • 3517 Score
  • 52 Answer
  • Tags:   javascript guid uuid

53 Answered Questions

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

37 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

Sponsored Content