`

JS 中的 public /private /priviliaged

阅读更多

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

Example

In this example, a person's name and race are set at birth and may never be changed. When created, a person starts out at year 1 and a hidden maximum age is determined for that person. The person has a weight which is modified by eating (tripling their weight) or exercising (halfing it). Every time the person eats or exercises, they grow a year older. The person object has a publicly accessible 'clothing' property which anyone can modify, as well as a dirtFactor which can be modified manually (throwing dirt on or scrubbing it off), but which increases every time the person eats or exercises, and is reduced by the use of the shower() method.

js 代码
 
  1. function Person(n,race){     
  2.     this.constructor.population++;    
  3. // ************************************************************************     
  4. // PRIVATE VARIABLES AND FUNCTIONS     
  5. // ONLY PRIVELEGED METHODS MAY VIEW/EDIT/INVOKE     
  6. // ***********************************************************************     
  7. var alive=true, age=1;     
  8. var maxAge=70+Math.round(Math.random()*15)+Math.round(Math.random()*15);     
  9. function makeOlder(){   
  10.     return alive = (++age <= maxAge)   
  11. }    
  12. var myName=n?n:"John Doe";     
  13. var weight=1;     
  14. // ************************************************************************     
  15. // PRIVILEGED METHODS     
  16. // MAY BE INVOKED PUBLICLY AND MAY ACCESS PRIVATE ITEMS     
  17. // MAY NOT BE CHANGED; MAY BE REPLACED WITH PUBLIC FLAVORS     
  18. // ************************************************************************     
  19. this.toString=this.getName=function(){ return myName }     
  20. this.eat=function(){         
  21.     if (makeOlder()){  
  22.                this.dirtFactor++;  
  23.                return weight*=3;         
  24.     } else   
  25.     alert(myName+" can't eat, he's dead!");     
  26. }     
  27. this.exercise=function(){         
  28.     if (makeOlder()){             
  29.         this.dirtFactor++;  
  30.         return weight/=2;         
  31.     } else   
  32.     alert(myName+" can't exercise, he's dead!");     
  33. }     
  34. this.weigh=function(){ return weight }     
  35. this.getRace=function(){ return race }     
  36. this.getAge=function(){ return age }     
  37. this.muchTimePasses=function(){ age+=50; this.dirtFactor=10; }  
  38. // ************************************************************************     
  39. // PUBLIC PROPERTIES -- ANYONE MAY READ/WRITE     
  40. // ************************************************************************     
  41. this.clothing="nothing/naked";     
  42. this.dirtFactor=0;}  
  43. // ************************************************************************  
  44. // PUBLIC METHODS -- ANYONE MAY READ/WRITE  
  45. // ************************************************************************  
  46. Person.prototype.beCool = function(){ this.clothing="khakis and black shirt" }  
  47. Person.prototype.shower = function(){ this.dirtFactor=2 }  
  48. Person.prototype.showLegs = function(){ alert(this+" has "+this.legs+" legs") }  
  49. Person.prototype.amputate = function(){ this.legs-- }  
  50. // ************************************************************************  
  51. // PROTOTYOPE PROERTIES -- ANYONE MAY READ/WRITE (but may be overridden)  
  52. // ************************************************************************  
  53. Person.prototype.legs=2;  
  54. // ************************************************************************  
  55. // STATIC PROPERTIES -- ANYONE MAY READ/WRITE  
  56. // ************************************************************************  
  57. Person.population = 0;  
  58. // Here is the code that uses the Person classfunction   
  59. RunGavinsLife(){     
  60.     var gk=new Person("Gavin","caucasian");//New instance of the Person object created.     
  61.     var lk=new Person("Lisa","caucasian"); //New instance of the Person object created.     
  62.     alert("There are now "+Person.population+" people");     
  63.     gk.showLegs(); lk.showLegs();//Both share the common 'Person.prototype.legs' variable when looking at 'this.legs'     
  64.     gk.race = "hispanic";  //Sets a public variable, but does not overwrite private 'race' variable.     
  65.     alert(gk+"'s real race is "+gk.getRace());    //Returns 'caucasian' from private 'race' variable set at create time.     
  66.     gk.eat(); gk.eat(); gk.eat();                 //weight is 3...then 9...then 27     
  67.     alert(gk+" weighs "+gk.weigh()+" pounds and has a dirt factor of "+gk.dirtFactor);     
  68.     gk.exercise();                                //weight is now 13.5     
  69.     gk.beCool(); //clothing has been update to current fashionable levels     
  70.     gk.clothing="Pimp Outfit";                    //clothing is a public variable that can be updated to any funky value     
  71.     gk.shower();     
  72.     alert("Existing shower technology has gotten "+gk+" to a dirt factor of "+gk.dirtFactor);     
  73.     gk.muchTimePasses();                          //50 Years Pass     
  74.     Person.prototype.shower=function(){           //Shower technology improves for everyone         
  75.         this.dirtFactor=0;     
  76.     }     
  77.     gk.beCool=function(){                         //Gavin alone gets new fashion ideas         
  78.         this.clothing="tinfoil";     
  79.     };     
  80.     gk.beCool();   
  81.     gk.shower();     
  82.     alert("Fashionable "+gk+" at "       +gk.getAge()+" years old is now wearing "       +gk.clothing+" with dirt factor "       +gk.dirtFactor);     
  83.     gk.amputate();                                //Uses the prototype property and makes a public property     
  84.     gk.showLegs(); lk.showLegs();                 //Lisa still has the prototype property     
  85.     gk.muchTimePasses();                          //50 Years Pass...Gavin is now over 100 years old.     
  86.     gk.eat();                                     //Complains about extreme age, death, and inability to eat.  
  87. }  

分享到:
评论

相关推荐

    ursa, node.js public/private 键的绑定.zip

    ursa, node.js public/private 键的绑定 URSA/public/private 键 注意:这个软件包是从 medium 和 NodePrime转移到 quartzjer到 JoshKaufman on 1 -2017. 欢迎请求请求来帮助维护它。- -This MOD

    SwiftyRSA, 在Swift中,RSA public/private 密钥加密.zip

    SwiftyRSA, 在Swift中,RSA public/private 密钥加密 SwiftyRSA Swift中的 public 密钥RSA加密。 在将驱动程序编号提交到之前,在 Scoop iOS应用程序中使用SwiftyRSA来加密驱动程序许可证编号。安装 Swift 3.2/4. 0

    JS中的public和private对象,即static修饰符

    在JavaScript中,public、private和static这些概念并非原生关键字,但可以通过特定的编码模式来实现类似的功能。在C#等静态类型语言中,public、private和static是访问修饰符,用于控制类成员的可见性和作用域。而在...

    oracle11g rac修改public ip/private ip/vip实施文档

    该文档记录了oracle11g rac修改public ip/private ip/vip的实施步骤

    PullScrollView

    public class PullBlurScrollView extends ScrollView { /**头部**/ private View mHeader; /**主体**/ private View mContentView; /** 模糊图片 **/ private BlurDrawable mBlurDrawable; /** 阻尼系数,越...

    面向对象修饰符public private protest super final abstract理解

    以上就是关于面向对象编程中`public`、`private`、`protected`、`final`、`abstract`、`super`和`this`等关键字的详细介绍。这些概念是面向对象编程的基础,掌握它们有助于更好地理解和应用面向对象的设计原则和技术...

    细谈Delphi中的private,public,protected

    ### Delphi中的访问控制修饰符:private,public,protected 在面向对象编程中,封装是保护数据完整性和安全性的核心原则之一。通过控制类成员(属性和方法)的可见性,我们可以有效地管理类的内部状态,并确保外部...

    jquery.datepicker-zh-CN.js

    &lt;script src="./public/js/jquery-ui-1.10.3.min.js"&gt;&lt;/script&gt; &lt;script src="./public/js/jquery.datepicker-zh-CN.js"&gt;&lt;/script&gt; &lt;link href="./public/css/jqueryui/jquery-ui-1.10.3.min.css" rel="stylesheet"&gt;...

    CircleIndicator

    public class CircleIndicator extends LinearLayout implements ViewPager.OnPageChangeListener{ private ViewPager mViewPager; ViewPager.OnPageChangeListener mListener; private final static int SCROLL_...

    PHP学生证查询管理系统_职业资格证防伪查询源码

    public/assets/js/frontend 对应的控制器名 public/assets/css public/index/js public/index/css 2.2 前台: application/index目录下 application/index/controller 控制器 application/index/lang 语言相关 ...

    java中public、protected、默认、private关键字

    Java 中有四种访问修饰符:public、protected、默认(default)和 private。这四种修饰符的作用域从大到小依次降低。 1. public 修饰符 public 修饰符是最宽松的访问修饰符,它允许从任何地方访问修饰的成员,...

    简单的PHP验证库.zip

    需要的朋友可以过来参考下class ValidateCode { ... public function __construct() {  $this-&gt;font = dirname(__FILE__).'/font/elephant.ttf';//注意字体路径要写对,否则显示不了图片  }

    learn_public_private.zip_learn c

    例如,在`learn_public_private.cpp`文件中,我们可能会看到这样的代码: ```cpp class MyClass { public: int publicVar; // 公有变量 void publicFunc() { // 公有函数 // 函数体 } }; int main() { ...

    delphi的Public,Private,Protected,Published作用域

    ### Delphi中的Public,Private,Protected,Published作用域详解 #### 一、引言 在面向对象编程中,封装是核心概念之一,它通过限制对类内部数据的直接访问来提高代码的安全性和可维护性。Delphi作为一种强大的...

    Laravel开发-laravel-php-elixir-combine

    Elixir由T Taylor Otwell开发,目的是简化常见的前端任务,如编译Sass、Less,或者处理JavaScript文件,使其在大型项目中更加便捷。在本教程中,我们将深入探讨如何使用Laravel Elixir来实现文件合并的功能。 标题...

    bibernate练习

    public class Department { private int id; private String name; // private Map,Employee&gt; emps; // private List&lt;Employee&gt; emps; private Set&lt;Employee&gt; emps; // private Employee[] emps; // //public Map...

    带时间的jquery日历控件

    &lt;script src="./public/js/jquery-ui-1.10.3.min.js"&gt;&lt;/script&gt; &lt;script src="./public/js/jquery.datepicker-zh-CN.js"&gt;&lt;/script&gt; &lt;script src="./public/js/jquery-ui-timepicker-addon.js"&gt;&lt;/script&gt; $( "#...

    分享/定位Activity天气预报方面的

    public View decorview; /** 接收定位界面城市数据 */ private static String citylocation; private Scoll scoll; /** 进度框 */ ProgressDialog pd; private static final String TAG = "demoActivity"; /...

    关于JavaScript作用域你想知道的一切

    这篇文章主要目的帮助理解JavaScript中的一些概念如:scope,closure, this, namespace, function scope, global scope, lexical scope and public/private scope. 希望从这篇文章中能回答如下的问题: 什么是作用域...

    一个ASP.NET的JS管理方案,防止重复引用JS问题

     /// 在控件Init的时候将JS路径添加到HttpContext.Current.Items["IncludedJavaScript"]中。  ///   ///   protected override void OnInit(EventArgs e)  {  base.OnInit(e);  if (!string....

Global site tag (gtag.js) - Google Analytics