0

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() {    
}
3

1 Answer 1

6

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.

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

4 Comments

subview is not initialized, will be undefined.. in the second version subview will not be available in the prototyped scope
@TJ, will subview be accessible in the prototype method?
@ArunPJohny & maček: Thanks, I was looking at the forest, hadn't gone back and looked at the trees.
Thanks... worked after initializing subview and using this with init.

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.