1

Is there a specific use of init() method in javascript?

Consider

var obj = {
    init: function(){
      return "Hello World";
   },
   foo: function(){
       return "Foo";
   }
}

Is there a difference between obj.init() v/s obj.foo()? Is it just a naming convention? Renaming init to main() has no effect. I realize that init is a naming convention that is used to place all of the initialization code for the object. Is that correct?

2
  • yes, that is correct. Commented Feb 28, 2014 at 23:06
  • Are you trying to implement some class-object-constructer stuff in Javascript? If so, I could post some sample code. Commented Feb 28, 2014 at 23:15

2 Answers 2

2

init has no special meaning in Javascript. It is just an ordinary valid identifier, like foo.

It is often used instead of initialize, because most developers know that init means initialize, and it's shorter to type. If you prefer, there would be no problems with using initialize instead.

Sign up to request clarification or add additional context in comments.

Comments

-1

Init has no special meaning in javascript. If you're looking for a constructor, in javascript you can call a function with the new keyword. This will create a 'new' this object and pass it to that function as the scope.

function obj(){
    this.foo = function() { 
       return "foo";
    }
}

var o = new obj(); // o.foo() returns "foo"

a lot of time people will use an init function to encapsulate the constructor functionality. It is common practice to also write an init function for setting up a plain object when you're not using a constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.