简体   繁体   English

javascript原型如何创建对象

[英]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. 我目前正在使用javascript学习原型,我写了以下内容,当我使用它时似乎工作正常。 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 . 您拥有的是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. 您要在将初始函数公开的同时将真正的私有范围保留给setObservables函数。 So every time you create a new instance of the constructor, your init function will always be in the prototype. 因此,每次创建构造函数的新实例时,您的init函数将始终位于原型中。 But setObservables will not. 但是setObservables不会。 In your example you could only access setObservables function internally (hence private scope). 在您的示例中,您只能在内部访问setObservables函数(因此为私有作用域)。 Usually you would do that if you only want your init function to call your private functions which in your case is setObservables. 通常,如果只希望init函数调用您的私有函数(在您的情况下为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. 现在,每次创建MyTest的新实例时,两个函数都将在其原型中。

var test = new MyTest(1, 2);
test.init();
test.setObservables();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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