简体   繁体   中英

javascript prototype how to create object

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' 

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM