2020 年更新
虽然在回答这个问题时,JavaScript 中的类还没有广泛使用,但现在情况已不再如此。 Most major browsers now support the ES2015 class syntax,随着 JavaScript 转译器的流行,它为那些不支持它的环境提供向后兼容性,类现在使用起来相当安全,并且对于那些从常见 OOP 语言转向 JavaScript 的人来说看起来更自然。
ES2015 类版本
class Abc {
constructor (aProperty, bProperty) {
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init();
}
init () {
// Initialization code here.
}
}
let currentAbc = new Abc(obj, obj);
私有版本与之前的版本大致相同,因为新类语法中没有提供可见性关键字
class Abc {
constructor (aProperty, bProperty) {
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init = function () {
// Initialization code here.
}
this.init();
}
}
let currentAbc = new Abc(obj, obj);
还有在闭包中创建类的选项,我相信一些编译器可能会这样做以确保函数在运行时是私有的。
const Abc = (function() {
function privateInit () {
// Do initialization here
}
return class Abc {
constructor (aProperty, bProperty) {
this.aProperty = aProperty;
this.bProperty = bProperty;
privateInit.call(this);
}
};
})();
const currentAbc = new Abc(obj, obj);
如果您使用的是 TypeScript 等超集,您可以简单地私下实现 init 函数,尽管这只是编译器检查,因此它可以保护您免受您自己的影响,而不是外部代码。
class Abc {
aProperty: any;
bProperty: any;
constructor (aProperty: any, bProperty: any) {
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init();
}
private init () {
// Initialization code here.
}
}
let currentAbc = new Abc(obj, obj);
原答案
也许是这样的?
var Abc = function(aProperty,bProperty){
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init = function(){
// Do things here.
}
this.init();
};
var currentAbc = new Abc(obj,obj);