问题
So, I just wanna know if anybody knows the particular meaning and usage of the init() statement in JavaScript, never really knew, kind of a newb.
回答1:
JavaScript doesn't have a built-in init()
function, that is, it's not a part of the language. But it's not uncommon (in a lot of languages) for individual programmers to create their own init()
function for initialisation stuff.
A particular init()
function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object, or...well, you name it.
What any given init()
does specifically is really up to whatever the person who wrote it needed it to do. Some types of code don't need any initialisation.
function init() {
// initialisation stuff here
}
// elsewhere in code
init();
回答2:
In JavaScript when you create any object through a constructor call like below
step 1 : create a function say Person..
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')
//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}
if you don't want to instantiate this function and call at same time.we can also do like 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 instantiating the object properties. basically init is like a constructor call on your class.
回答3:
NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass
instead of myClass
.
Either you can call init
from your 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 more simply you could just copy the body of the init
function to the end of the constructor function. No need to actually have an init
function at all if it's only called once.
来源:https://stackoverflow.com/questions/7884081/what-is-the-use-of-the-init-usage-in-javascript