简体   繁体   English

Javascript类构造函数调用方法

[英]Javascript Class Constructor Call Method

In Java you could call methods to help you do some heavy lifting in the constructor, but javascript requires the method to be defined first, so I'm wondering if there's another way I could go about this or if I'm forced to call the method that does the heavy lifting after it's been defined. 在Java中你可以调用方法来帮助你在构造函数中做一些繁重的工作,但javascript需要首先定义方法,所以我想知道是否有另一种方法可以解决这个问题,或者我是否被迫调用在定义之后进行繁重的方法。 I prefer to keep instance functions contained within the Object/Class, and it feels weird that I would have to have the constructor at the very end of the object/class. 我更喜欢保持Object / Class中包含的实例函数,并且我必须在对象/类的最末端拥有构造函数,这感觉很奇怪。

function Polynomials(polyString)
{
    // instance variables
    this.polys = [];
    this.left = undefined;
    this.right = undefined;

    // This does not work because it's not yet declared
    this.parseInit(polyString);

    // this parses out a string and initializes this.left and this.right
    this.parseInit = function(polyString)
    {
        //Lots of heavy lifting here (many lines of code)
    }

    // A lot more instance functions defined down here (even more lines of code)

    // Is my only option to call it here?
}

Here's what I would do: 这就是我要做的事情:

var Polynomials = function() { 
   // let's use a self invoking anonymous function
   // so that we can define var / function without polluting namespace
   // idea is to build the class then return it, while taking advantage
   // of a local scope.

   // constructor definition
   function Polynomials( value1) (
      this.property1 = value1;
      instanceCount++;
      // here you can use publicMethod1 or parseInit
   }

   // define all the public methods of your class on its prototype.
   Polynomials.prototype = {

     publicMethod1 : function() { /* parseInit()... */ },

     getInstanceCount : function() ( return instanceCount; }

   }

  // you can define functions that won't pollute namespace here
  // those are functions private to the class (that can't be accessed by inheriting classes)
  function parseInit() {
  }

  // you can define also vars private to the class
  //  most obvious example is instance count.
  var instanceCount = 0; 

   // return the class-function just built;
   return Polynomials;

}();

Remarks: 备注:

Rq 1: Rq 1:

prototype functions are public methods available for each instance of the class. 原型函数是可用于每个类实例的公共方法。

var newInstance = new MyClass();
newInstance.functionDefinedOnPrototype(sameValue);

Rq2: If you want truly 'private' variable, you have to got this way: Rq2:如果你想要真正的'私人'变量,你必须这样:

function Constructor() {
   var privateProperty=12;
   this.functionUsingPrivateProperty = function() {  
    // here you can use privateProperrty, it's in scope
   }
}

Constructor.prototype = {
    // here define public methods that uses only public properties
    publicMethod1 : function() {
        // here privateProperty cannot be reached, it is out of scope.
    }
}

personally, I do use only properties (not private vars), and use the ' ' common convention to notify a property is private. 就个人而言,我只使用属性(不是私有变量),并使用' '通用约定来通知属性是私有的。 So I can define every public method on the prototype. 所以我可以在原型上定义每个公共方法。
After that, anyone using a property prefixed with ' ' must take his/her responsibility , it seems fair. 在此之后,任何使用前缀为' ' 的财产的人都必须承担他/她的责任,这似乎是公平的。 :-) :-)

For the difference between function fn() {} and var fn= function() {} , google or SO for this question, short answer is that function fn() {} gets the function defined and assigned its value in whole scope, when var get the var defined, but its value is only evaluated when code has run the evaluation. 对于function fn() {}var fn= function() {}之间的区别,google或SO对于这个问题,简短的回答是function fn() {}获取定义的函数并在整个范围内赋值, var获取定义的var,但仅在代码运行评估时评估其值。

Your 'instance variables' are declared on the 'this' object which if you're looking for a Java equivalent is a bit like making them public. 您的'实例变量'在'this'对象上声明,如果您正在寻找Java等价物,有点像将它们公开。 You can declare variables with the var keyword which makes them more like private variables within your constructor function. 您可以使用var关键字声明变量,这使得它们更像构造函数中的私有变量。 Then they are subject to 'hoisting' which basically means they are regarded as being declared at the top of your function (or whatever scope they are declared in) even if you write them after the invoking code. 然后它们受到“提升”的约束,这基本上意味着它们被认为是在函数的顶部声明(或者声明它们的任何范围),即使你在调用代码之后编写它们也是如此。

I would create a function declaration and then assign the variable to the function declaration. 我将创建一个函数声明,然后将该变量赋值给函数声明。 The reason being that JavaScript will hoist your function declarations. 原因是JavaScript将提升你的函数声明。

So you could do this: 所以你可以这样做:

function Polynomials(polyString) {
    // instance variables
    this.polys = [];
    this.left = undefined;
    this.right = undefined;

    // this parses out a string and initializes this.left and this.right
    this.parseInit = parseInitFunc;

    // This does not work because it's not yet declared
    this.parseInit(polyString);

    // A lot more instance functions defined down here (even more lines of code)

    function parseInitFunc(polyString) {
        console.log('executed');
    }

    // Is my only option to call it here?
}

That way your code stays clean. 这样你的代码就会保持干净。

jsFiddle 的jsfiddle

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

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