ALBI
ALBI

Reputation: 721

Calling function of instances in Javascript

I am trying create a hashmap in View function having instances of subviews , which I do in init method of View. But it is giving an error that init() of view doesnt exist. Am I doing anything wrong here? Thanks in advance.

http://jsfiddle.net/3fR4R/1/

view = function() {
    var subview;
    init = function() {
        subview['search'] = new searchSubView();
    }
}

check = function() {
    console.log("clicked");
    var view1= new view();
    view1.init();
}

searchSubView = function() {    
}

Upvotes: 0

Views: 66

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074979

You've created a function and assigned it to an implicit global, which has nothing to do with the view function or instances created by it.

You can assign the function either by assigning to this.init within the constructor, or by putting it on view.prototype.

So either:

view = function() {
    var subview;

    // Note: You need code here to initialize `subview`

    this.init = function() {
        subview['search'] = new searchSubView();
    };
};

or (note that I've made subview a property):

view = function() {
    this.subview = /* ...initialize subview... */;
};
view.prototype.init = function() {
    this.subview['search'] = new searchSubView();
};

Side notes:

  1. You're falling prey to The Horror of Implicit Globals a lot in that code. You need to declare variables.

  2. The overwhelming convention in JavaScript code is to use initial capitals for constructor functions, e.g., View rather than view.

  3. You're also relying on automatic semicolon insertion, which I wouldn't recommend. Learn the rules and apply them, not least so you can minify/compress/compact your code safely.

Upvotes: 6

Related Questions