开发者

How is privacy achieved here?

Could someone tell me how the public and private methods are achiveved in this开发者_Python百科 example code for a simple animation library from dustin Diaz. How are the private methods distinguished from the public one?

http://www.dustindiaz.com/javascript-animate/


It's just privacy by convention - he's put an underscore before the method name, which is his way of saying "this method is private, don't call it".


It isn't; there is no visibility in Javascript aside from scope. Those specifications in the example are based off of method nomenclature and purpose only.


In short:

Summary

  • private variables are declared with the var keyword inside the object, and can only be accessed by private functions and privileged methods.

  • private functions are declared inline inside the object's constructor (or alternatively may be defined via var functionName=function(){...}) and may only be called by privileged methods (including the object's constructor).

  • privileged methods are declared with this.methodName=function(){...} and may invoked by code external to the object.

  • public properties are declared with this.variableName and may be read/written from outside the object.

  • public methods are defined by Classname.prototype.methodName = function(){...} and may be called from outside the object.

  • prototype properties are defined by Classname.prototype.propertyName = someValue

  • static properties are defined by Classname.propertyName = someValue

You can read an excellent article here:

http://javascript.crockford.com/private.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜