zoukankan      html  css  js  c++  java
  • OOP in JS Public/Private Variables and Methods

    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

    (different between static and prototype properties)

    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.

    The Example Code

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

    Notes

    • maxAge is a private variable with no privileged accessor method; as such, there is no way to publicly get or set it.
    • race is a private variable defined only as an argument to the contructor. Variables passed into the constructor are available to the object as private variables.
    • The 'tinfoil' beCool() fashion method was applied only to the gk object, not the entire Personclass. Other people created and set to beCool() would still use the original 'khakis and black shirt' clothing that Gavin eschewed later in life.
    • Note the implicit call to the gk.toString() method when using string concatenation. It is this which allows the code alert(gk+' is so cool.') to put the word 'Gavin' in there, and is equivalent to alert(gk.toString()+' is so cool.'). Every object of every type in JS has a.toString() method, but you can override it with your own.
    • You cannot (to my knowledge) assign public methods of a class inside the main object constructor...you must use the prototype property externally, as above with the beCool() andshower() methods.
    • As I attempted to show with the Person.prototype.legs property and the amputate() function, prototype properties are shared by all object instances. Asking for lk.legs yields '2' by looking at the single prototype property. However, attempting to change this value using either gk.legs=1or (in the Person object) this.legs=1 ends up making a new public property of the object specific to that instance. (This is why calling gk.amputate() only removed a leg from Gavin, but not Lisa.) To modify a prototype property, you must use Person.prototype.legs=1 or something likethis.constructor.prototype.legs=1. (I say 'something like' because I discovered thatthis.constructor is not available inside private functions of the object, since this refers to the window object in that scope.)
    • Wherever an anonymous function is declared inline with
      foo = function(p1,p2){ some code }
      the new Function() constructor is NOT equivalent, e.g.
      foo = new Function('p1','p2','code');
      since the latter runs in the global scope--instead of inheriting the scope of the constructor function--thus preventing it from accessing the private variables.
    • As noted above in the code comments, the act of setting gk.race to some value did NOT overwrite the private race variable. Although it would be a dumb idea, you can have both private and public variables with the same name. For example, the yell() method in the following class will yield different values for foo and this.foo:
      function StupidClass(){ 
        var foo = "internal";
        this.foo = "external";
        this.yell=function(){ alert("Internal foo is "+foo+"
      External foo is "+this.foo) }
    • Private functions and privileged methods, like private variables and public properties, are instantiated with each new object created. So each time new Person() is called, new copies ofmakeOlder()toString()getName()eat()exercise()weigh()getRace()getAge(), and muchTimePasses() are created. For every Person, each time. Contrast this with public methods (only one copy of beCool() and shower() exist no matter how many Person objects are created) and you can see that for memory/performance reasons it can be preferable to give up some degree of object protection and instead use only public methods.

    Note that doing so requires making private variables public (since without privileged accessor methods there would be no way to use them) so the public methods can get at them...and which also allows external code to see/destroy these variables. The memory/performance optimization of using only public properties and methods has consequences which may make your code less robust.

    For example, in the above age and maxAge are private variables; age can only be accessed externally through getAge() (it cannot be set) and maxAge cannot be read or set externally. Changing those to be public properties would allow any code to do something like gk.maxAge=1; gk.age=200; which not only does it not make sense (you shouldn't be able to manipulate someone's age or lifespan directly), but by setting those values directly the alive variable wouldn't properly be updated, leaving your Person object in a broken state.

    Quote From:

    OOP in JS, Part 1 : Public/Private Variables and Methods

    See Also:

    Object-Oriented JavaScript Tip: Creating Static Methods, Instance Methods

    How To Get Private, Privileged, Public And Static Members (Properties And Methods)

  • 相关阅读:
    Ubuntu 环境变量
    UBoot命令介绍
    如何在内核里面查找某些结构体或者宏的定义
    linux core dump
    右下角弹出广拦截程序(迅雷,搜狐,腾讯)
    aptfile 安装包文件搜索
    Windows 7操作系统中使用IIS,WinScp搭建ftp服务器
    UltraEdit文本编辑利器
    SSIS高级转换任务—导出列
    SSIS高级转换任务—在Package中是用临时表是需要设置RetainSameConnection属性
  • 原文地址:https://www.cnblogs.com/liao-hua/p/4672141.html
Copyright © 2011-2022 走看看