在 Java 中,您可以调用方法来帮助您在构造函数中完成一些繁重的工作,但是 javascript 要求首先定义该方法,所以我想知道是否有其他方法可以解决这个问题,或者我是否被迫在定义之后调用执行繁重工作的方法。我更喜欢将实例函数包含在对象/类中,而且我不得不将构造函数放在对象/类的最后面感觉很奇怪。
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?
}
最佳答案
这是我会做的:
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;
}();
备注:
要求 1:
原型(prototype)函数是可用于类的每个实例的公共(public)方法。
var newInstance = new MyClass();
newInstance.functionDefinedOnPrototype(sameValue);
问题 2: 如果你想要真正的“私有(private)”变量,你必须这样:
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.
}
}
就个人而言,我只使用属性(不是私有(private)变量),并使用“”通用约定来通知属性是私有(private)的。所以我可以在原型(prototype)上定义每个公共(public)方法。
之后,任何使用前缀为“”的属性的人都必须承担他/她的责任,这似乎是公平的。 :-)
对于function fn() {}
和var fn= function() {}
的区别,google或者S.O.对于这个问题,简短的回答是 function fn() {}
获取定义的函数并在整个范围内分配它的值,当 var
获取定义的 var 时,但它的值仅在代码运行评估时评估。
关于Javascript类构造函数调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24352909/