相关疑难解决方法(0)

Javascript:我应该隐藏我的实现吗?

作为一名C#程序员,我有一种习惯,就是把私事空间变得私密,当JS类型将所有私密部分暴露给我时,我总会有一种奇怪的感觉(并且这种感觉不会被'唤起' ).说我有具有一种draw方法,它在内部调用drawBackgrounddrawForeground,这是毫无意义要对自己的调用.我该如何实现呢?

选项1

Foo = function(){
  this.draw();  
};

Foo.prototype.draw = function(){
  this.drawBackground();
  this.drawForeground();
};

Foo.prototype.drawBackground = function(){};
Foo.prototype.drawForeground = function(){};
Run Code Online (Sandbox Code Playgroud)

选项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;

})();
Run Code Online (Sandbox Code Playgroud)

当然,不同之处在于,在第一个示例中,drawBackgrounddrawForeground方法是公共API的一部分,而在第二个示例中它们被隐藏到外部.这是可取的吗?我应该选择哪一个?将我的C#习惯应用于Javascript我是错误的,我应该在Javascript中使所有内容都可扩展和覆盖吗?那性能影响是.call(this)什么?

javascript oop prototype private-members

5
推荐指数
1
解决办法
152
查看次数

标签 统计

javascript ×1

oop ×1

private-members ×1

prototype ×1