What is the use of using init () in JavaScript?

So, I just want to know if anyone knows the specific meaning and use of the init () instruction in JavaScript, never knew like newb.

+43
javascript init
Oct. 25 '11 at 2:32
source share
3 answers

JavaScript does not have a built-in init() function, that is, it is not part of the language. But it is not uncommon (in many languages) for individual programmers to create their own init() function for initialization material.

A specific init() function can be used to initialize the entire web page, in which case it will probably be called from document.ready or onload processing, or a specific type of object can be initialized or ... well, call it.

What any given init() does specifically depends on the fact that the person who wrote it needed it. Some types of code do not need initialization.

 function init() { // initialisation stuff here } // elsewhere in code init(); 
+83
Oct 25 '11 at 2:59 a.m.
source share

In JavaScript, when you create any object through a constructor call, as shown below

Step 1: create a say Person function ..

 function Person(name){ this.name=name; } person.prototype.print=function(){ console.log(this.name); } 

Step 2: create an instance for this function.

 var obj=new Person('venkat') 

// this function (Person) will be created above the line and return a new Person object (name: 'venkat'}

if you do not want to instantiate this function and call at the same time. We can also do as below.

 var Person = { init: function(name){ this.name=name; }, print: function(){ console.log(this.name); } }; var obj=Object.create(Person); obj.init('venkat'); obj.print(); 

in the above method, init will help in creating the properties of the object. basically init is like calling the constructor of your class.

+16
Jan 14 '16 at 4:08
source share

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, for example. MyClass instead of MyClass .

You can call init from the constructor function:

var myObj = new MyClass(2, true); function MyClass(v1, v2) { // ... // pub methods this.init = function() { // do some stuff }; // ... this.init(); // <------------ added this }

Or, simply put, you can simply copy the body of the init function to the end of the constructor function. There is no need to have an init function at all if it is only called once.

-one
May 10 '17 at 6:48
source share



All Articles