作为一名C#程序员,我有一个习惯,即将可以和应该私有化的东西私有化。当一个JS类型向我展示它的所有私有部分时(这种感觉并不是“被激起的”),我总是感到奇怪。假设我有一个类型,它有一个
draw
方法,内部调用drawBackground
和drawForeground
,这些方法单独调用没有意义。那么我该如何实现呢?
选项1:
Foo = function(){
this.draw();
};
Foo.prototype.draw = function(){
this.drawBackground();
this.drawForeground();
};
Foo.prototype.drawBackground = function(){};
Foo.prototype.drawForeground = function(){};
选项二
Foo = (function(){
var constructor = function(){
this.draw();
};
var drawBackground = function(){};
var drawForeground = function(){};
constructor.prototype.draw = function(){
drawBackground.call(this);
drawForeground.call(this);
};
return constructor;
})();
当然,第一个例子中,drawBackground
和 drawForeground
方法是公共API的一部分,而在第二个例子中它们对外部隐藏。这是可取的吗?我应该选择哪一个?我是否错误地将我的C#习惯应用于Javascript,并且应该在Javascript中使所有内容都可扩展和覆盖?.call(this)
的性能影响是什么?