1

I'm currently learning prototyping in javascript, i wrote the below and it seems to work fine when i use it. my question was why do i need the () at the end of the prototype declaration, without that if i try to make an instance of the object I get an error.

var MyTest = function (agencyId, dataId) {
this.agencyId= agencyId;
this.dataId= dataId;
};

MyTest.prototype = function () {
    var setObservables = function () {
        ...
    },
    init = function (url) {
        ...
    };

    // public members
    return {
        init: init
    };  
}();

to use it I call it like

            var obj = new DetailsDivisionKO(1, 2);
        obj.init(actionUrl);

this works fine, but I'm confused about the }(); at the end of the public members section, why is that needed and I can not have that and still use the above code to call it? As without that if i try to call the above code I get a error stating:

Uncaught TypeError: Object [object Object] has no method 'init' 
2
  • 3
    The prototype needs to be an Object, the () is invoking the function expression so the Object is returned Commented Jan 7, 2014 at 18:53
  • 2
    You are creating a function and then immediately calling it. This is done to create a new scope. Commented Jan 7, 2014 at 18:55

1 Answer 1

4

What you have is an IIFE. Its an imidiately invoked function. You are basically creating a closure. You are exposing your init function while preserving a true private scope to your setObservables function. So every time you create a new instance of the constructor, your init function will always be in the prototype. But setObservables will not. In your example you could only access setObservables function internally (hence private scope). Usually you would do that if you only want your init function to call your private functions which in your case is setObservables. But if this is not what you want, you simply can do this:

  var MyTest = function (agencyId, dataId) {
   this.agencyId= agencyId;
   this.dataId= dataId;
  };

  MyTest.prototype = {
     setObservables: function () {
         ...
     },
     init: function (url) {
         ...
     }
  }

Now every time you will create a new instance of MyTest, both of your functions will be in its prototype.

var test = new MyTest(1, 2);
test.init();
test.setObservables();
Sign up to request clarification or add additional context in comments.

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.