How to init function?

Need help how to init function?
An error occurs: Uncaught ReferenceError: formInit1 is not defined

<!DOCTYPE HTML>
<html>
<head>
	<meta http-equiv="content-type" content="text/html" />
	<title>Initi function</title>
</head>

<body>

<script type="text/javascript">


var formInit1 = (function ()
 {
  function init() {



  }
  return {
   init
  };
 }()
);
</script>
<script>formInit1.init();</script>
</body>
</html>
var formInit1 = ( function () {
  function init() {



  }

  return { init };
}());

formInit1.init() // to execute the init function

The above is called the Revealing Module Pattern

One advantage of this pattern apart from being able to organise your code into modules, is that it allows for private variables.

const formInit = (function () {
  // private variable
  let count = 0

  function init() {
    count += 1 // increase count each time init is called
    
  }

  function logCount () {
    console.log(count);
  }

  // this will be what is assigned to formInit
  return { init, logCount };
}());

formInit.init()
formInit.logCount() // 1
formInit.init()
formInit.logCount() // 2

// count is not accesible and cannot be changed outside of the 
// formInit object
console.log(formInit.count) // undefined
console.log(count) // Uncaught ReferenceError: count is not defined

This is a little outdated, (the ‘var’ you have used is a bit of a giveaway). It is still worth learning about and I would include learning about ‘closures’.

These days you can just use modules.

BTW: I just tested your code, adding a console.log inside of the init function e.g.

function init() {
  console.log('I am working!!')
}

and it outputed ‘I am working!!’, so it seems to work for me.

2 Likes

But this is no longer needed as we now have real modules and classes in ES6 which is much more readable and easier to understand

3 Likes

Thank you for the message!
It works now when I validated.

1 Like

But this is no longer needed as we now have real modules and classes in ES6 which is much more readable and easier to understand.

Can you please send us an example of classes and modules inside WordPress framework? As I understand Laravel has an option by default. Another option is to move from init functions to Angular framework which uses modules?

I’ll refer to the last bit in my post

This is a little outdated, (the ‘var’ you have used is a bit of a giveaway). It is still worth learning about and I would include learning about ‘closures’.

These days you can just use modules.

javascript.info

Modules, introduction

I still think it doesn’t hurt to understand where modules originated from in JS, and some of the techniques used to encapsulate code, such as making use of closures.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.