Javascript: should I be hiding my implementations?

情到浓时终转凉″ 提交于 2019-12-10 14:48:19

问题


As a C# programmer, I have a bit of a habit of making things private that can and should be private, and I always get a weird feeling when a JS type exposes all its private parts to me (and that feeling is not 'aroused'). Say I have a type that has a draw method, which internally calls drawBackground and drawForeground, which make no sense to be called on their own. How should I implement this?

Option 1

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

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

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

Option 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;

})();

The difference, of course, being that in the first example, the drawBackground and drawForeground methods are part of the public API, while they are hidden to the outside in the second one. Is that desirable? Which one should I prefer? Am I wrong to apply my C# habits to Javascript and should I make everything extensible and override-able in Javascript? And what are the performance implications of the .call(this)?


回答1:


There's a well known quote amongst Perl developers that comes from the (in)famous Camel book: "A Perl module would prefer that you stay out of its living room because you weren't invited, not because it has a shotgun.". The philosophy being, if you as the developer of a library want to distinguish between your public and private API, that's great. Do that and document it. The caller of your code should know which is which, but also be free to act like an idiot if they decide to and call things you don't think they should call. From an OO background, that's heretical, but with scripting languages, that's how they roll.

The answer to this is a bit subjective, but I'll tell you that when I'm writing JavaScript and have methods or variables that would be private if I were coding in .NET, I just prefix them with something like "prv_" or "p_" or just "_"... whatever floats your boat. That way, you've told your users that this stuff is meant to be private and could change out from under them. And that way, if they choose to call your private methods anyway, that iffy code will stick out like a sore thumb.



来源:https://stackoverflow.com/questions/3220870/javascript-should-i-be-hiding-my-implementations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!