作为一名 C# 程序员,我有点习惯将可以而且应该是私有的东西设为私有,当 JS 类型将其所有私有部分暴露给我时,我总是有一种奇怪的感觉(而且这种感觉并没有被“激发” )。假设我有一个类型,它有一个draw
方法,它在内部调用drawBackground
and drawForeground
,单独调用是没有意义的。我应该如何实现这个?
选项1
Foo = function(){
this.draw();
};
Foo.prototype.draw = function(){
this.drawBackground();
this.drawForeground();
};
Foo.prototype.drawBackground = function(){};
Foo.prototype.drawForeground = function(){};
选项 2
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
anddrawForeground
方法是公共 API 的一部分,而在第二个示例中它们是隐藏在外部的。这是可取的吗?我应该更喜欢哪一个?将我的 C# 习惯应用到 Javascript 是否是错误的,我是否应该在 Javascript 中使所有内容都可扩展和覆盖?的性能影响是.call(this)
什么?