SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: Init method

  1. #1
    SitePoint Member
    Join Date
    Jun 2012
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Init method

    The author of Simply JavaScript uses the method of init for objects. But then I read that it is not a keyword in JavaScript. I am very confused. Do we have to define the init keyword first. Hopefully, someone can free me from this confusion.i

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,387
    Mentioned
    45 Post(s)
    Tagged
    12 Thread(s)
    Yeah you're right, this method doesn't exist on objects in JS by default. It's common to add convenience methods like this to make object creation easier. An init method is sometimes added by developers as a kind of 'secondary constructor' - you can see an example of this with libraries such as Backbone.js, where you create new view objects like this:

    Code JavaScript:
    var ListItemView = Backbone.View.extend({
     
        tagName: 'li',
     
        initialize: function() {
            this.listenTo(this.model, "change", this.render);
        },
     
        // ...
    });
     
    var myListItem = new ListItemView;  // Initialize function will be called.
    Here the object's real constructor does the work of setting up object defaults and such behind the scenes, and then calls the user-defined initialize method (if it exists) to do any other object configuration that you might need.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •