好!欢迎访问迷津渡口 现在时间是: 天气 °C ~ °C

迷津渡口

越感到迷惑 越接近真理

javascript中私有变量,特权函数和闭包详解

开篇立原则:

1.javascript中一切都是对象。
2.对象的私有变量或函数里的局部变量与世隔绝。
3.函数可为右值。
4.函数执行环境可保存。
5.函数普通返回值为值传递。

对象私有变量和特权函数

在对象构造函数或者方法里面出现的局部变量就是对象的私有变量。

这些私有变量和私有属性或普通属性不同,无法通过对象直接获取,形成一种与世隔绝的状态。

私有变量只能通过定义特权方法函数获取和修改。

例子:

function Test(propertyA) {
    // 普通属性propertyA
    this.propertyA=propertyA;
    // 普通属性设置方法
    this.setPropertyA=function(pushA) {
        this.propertyA=pushA;
    };
    // 普通属性获取方法
    this.getPropertyA=function() {
        console.log(this.propertyA);
    };
    
    // 私有变量localPropertyB
    var localPropertyB='secret';
    // 配置特权方法设置私有变量localPropertyB
    this.setLocalPropertyB=function(pushB) {
        localPropertyB=pushB;
    };
    // 配置特权方法获取私有变量localPropertyB
    this.getLocalPropertyB=function() {
        console.log(localPropertyB);
    };
}
// 实例化对象
var test=new Test('normal');
// 直接利用对象获取普通属性
console.log(test.propertyA);
// 直接利用对象修改普通属性
test.propertyA='new normal';
// 直接获取修改后的属性
console.log(test.propertyA);
// 利用对象方法修改普通属性
test.setPropertyA('new new normal');
// 利用对象方法获取普通属性
test.getPropertyA();

// 尝试利用对象获取私有变量
// 当然不行,句点.符号只能获取属性
// test对象没有localPropertyB属性
// 因此只能输出undefined喽
console.log(test.localPropertyB);
// 利用对象的特权方法获取对象的私有变量
test.getLocalPropertyB();
// 利用对象的特权方法修改对象的私有变量
test.setLocalPropertyB('new secret');
// 再次利用特权方法获取修改后的私有变量
test.getLocalPropertyB();

结果为:

normal
new normal
new new normal
undefined
secret
new secret

利用对象中私有变量这种与世隔绝的状态,我们可以定义隐藏变量,只可以通过接口特权函数获取和修改。

函数局部变量和闭包

相对于对象的构造函数里的私有变量,普通函数里面的局部变量同样具有与世隔绝的状态。

此时可以利用所谓的闭包获取和修改局部变量,从而作出相应不同的处理。

先上三个例子,总结在后面~

例一:在闭包函数里直接同时修改和获取局部变量

function test() {
    var x = 1;

    function setGetX() {
      	++x;
      	console.log(x);
    }

    return setGetX;
}
var outTest=test();
outTest();
outTest();
var outTest1=test();
outTest1();
outTest();
outTest();
outTest1();

结果为:

2
3
2
4
5
3

例二:在闭包函数里利用私有函数同时修改和获取局部变量

function test() {
    var x = 1;

    function setX() {
        ++x;
    }

    function getX() {
        console.log(x);
    }
    function setGetX() {
      	setX();
       	getX();
    }

    return setGetX;
}
var outTest=test();
outTest();
outTest();
var outTest1=test();
outTest1();
outTest();
outTest();
outTest1();

结果为:

2
3
2
4
5
3

例三:根据参数获取不同闭包函数分别修改和获取变量

function test(type) {
    var x = 1;
    
    function setX() {
        ++x;
    }
    
    function getX() {
        console.log(x);
    }
    
    return (type === 'set')?setX:getX;
}
var outSetTest=test('set');
var outGetTest=test('get');
outGetTest();
outSetTest();
outGetTest();

结果为:

1
1

例子总结:

1.闭包可以保留函数的执行环境,包含变量和引用的局部函数环境。
2.同一个实例化的闭包可以修改局部变量并不断累积,此时的局部变量具有类似static静态变量的效果。
3.不同实例化的闭包之间互不影响,修改的局部变量也不会互相影响。


小指才疏学浅,任何不妥之处,请不吝赐教~

点赞2
   支持一下
挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
 点赞
 签到
 表情
 图片
 代码
提交评论

清空信息
关闭评论
amrservicio
 amrservicio 约 17 小时前回复
#123
<a href="http://www.elifeinsnow.com/nike-mercurial-viii-skor">nike mercurial viii</a> <a href="http://www.tsgctt.com/philip-rivers-game-worn-jersey-nflr">philip rivers game worn jersey</a> <a href="http://www.satonni.com/oakland-raiders-15-michael-crabtree-olive-2017-salute-to-service-limited-jersey-nflv">oakland raiders 15 michael crabtree olive 2017 salute to service limited jersey</a> <a href="http://www.inenigroup.com/red-black-polo-ralph-lauren-shirt-polor">red black polo ralph lauren shirt</a> <a href="http://www.nowminning.com/bon-march%C3%A9-nike-huarache-utility-femmes-trainersce">bon march茅 nike huarache utility femmes</a> <a href="http://www.mytopdollar.com/buy-ray-ban-cats-5000-sunglassesr">buy ray ban cats 5000</a>
amrservicio http://www.amrservicio.com/
poppiesdelray
 poppiesdelray 2019-03-19 01:15回复
#122
<a href="http://www.mistopup.com/nike-air-max-hvit-l%C3%A6r-mennns-obuvj">nike air max hvit l忙r mennns</a> <a href="http://www.sporbahispro.com/nike-huarache-utility-viola-scarpel">nike huarache utility viola</a> <a href="http://www.kalrakis.com/nike-air-huarache-bleu-orange-chaussuresh">nike air huarache bleu orange</a> <a href="http://www.xinyudaili.com/maschio-nike-dunk-high-blu-nero-gituttio-arancia-scarpeh">maschio nike dunk high blu nero gituttio arancia</a> <a href="http://www.marieluwasche.com/miami-heat-back-in-black-jersey-nfli">miami heat back in black jersey</a> <a href="http://www.ferrepress.com/mujer-nike-air-huarache-negro-blanco-zapatosh">mujer nike air huarache negro blanco</a>
poppiesdelray http://www.poppiesdelray.com/
industrialamps
 industrialamps 2019-03-17 18:36回复
#121
<a href="http://www.bursatiket.net/nike-blazer-low-suede-trainers-blu-kurpesc">nike blazer low suede trainers blu</a> <a href="http://www.buxpix.net/air-jordan-3-true-bleu-for-vente-florida-schuhea">air jordan 3 true bleu for vente florida</a> <a href="http://www.buyggauto.net/adidas-neo-baby-sko-kurpesf">adidas neo baby sko</a> <a href="http://www.carlinandcompany.net/nike-zoom-pegasus-31-azul-negro-chaussuresa">nike zoom pegasus 31 azul negro</a> <a href="http://www.carrymebike.net/nike-zoom-pegasus-33-kvinners-gull-r%C3%B8d-kurpesg">nike zoom pegasus 33 kvinners gull r酶d</a> <a href="http://www.casatienda.net/hommes-nike-roshe-run-hyperfuse-or-schuhee">hommes nike roshe run hyperfuse or</a>
industrialamps http://www.industrialamps.net/
mysiatravel
 mysiatravel 2019-03-17 18:26回复
#120
<a href="http://www.ucllnl.com/denver-broncos-tramaine-brock-youth-limited-orange-nike-jersey-22-nfl-rush-vapor-untouchable-nflw">denver broncos tramaine brock youth limited orange nike jersey 22 nfl rush vapor untouchable</a> <a href="http://www.ugurcafe.com/air-jordan-retro-7-blanc-orange-noir-butye">air jordan retro 7 blanc orange noir</a> <a href="http://www.destinyrail.com/new-balance-999-cielo-blu-nero-kurpesd">new balance 999 cielo blu nero</a> <a href="http://www.dinerwarela.com/lila-wei%C3%9F-ralph-lauren-stripe-shirt-polo-cotton-dam%C3%A4nner-polos">lila wei脽 ralph lauren stripe shirt polo cotton dam盲nner</a> <a href="http://www.kalaycioto.com/nike-air-force-1-30th-anniversary-sort-r%C3%B8d-butyf">nike air force 1 30th anniversary sort r酶d</a> <a href="http://www.krystaltls.com/ralph-lauren-check-stretch-cotton-shirt-light-blu-polou">ralph lauren check stretch cotton shirt light blu</a>
mysiatravel http://www.mysiatravel.com/
chromacell
 chromacell 2019-03-17 17:16回复
#119
<a href="http://www.cultureofwine.net/adidas-nitrocharge-blau-knight-chaussuresf">adidas nitrocharge blau knight</a> <a href="http://www.cundinamarca.net/air-jordan-reveal-gul-rosa-obuvc">air jordan reveal gul rosa</a> <a href="http://www.darkstories.net/air-jordan-retro-12-french-blu-2016-kurpesb">air jordan retro 12 french blu 2016</a> <a href="http://www.davidgosse.net/nike-foamposite-dark-obsidian-for-verkauf-kurpese">nike foamposite dark obsidian for verkauf</a> <a href="http://www.desmotivaciones.net/new-blance-500-ni%C3%B1os-oro-marr%C3%B3n-kurpesd">new blance 500 ni帽os oro marr贸n</a> <a href="http://www.didaar.net/air-max-1-polarized-blau-scarped">air max 1 polarized blau</a>
chromacell http://www.chromacell.net/
arealleader
 arealleader 2019-03-17 05:42回复
#118
<a href="http://www.awassessment.com/adidas-tout-noir-nitrocharge-chaussuresl">adidas tout noir nitrocharge</a> <a href="http://www.websiteopmaat.com/nike-air-max-90-m%C3%A4nner-schwarz-wei%C3%9F-photo-blau-schuhej">nike air max 90 m盲nner schwarz wei脽 photo blau</a> <a href="http://www.lopifitfl.com/nike-sandals-rot-and-schwarz-schuhei">nike sandals rot and schwarz</a> <a href="http://www.aurorefleurs.com/nike-air-force-1-hvit-gum-obuvj">nike air force 1 hvit gum</a> <a href="http://www.ezedcal.com/nike-air-max-tn-maschio-nero-bianca-rosso-scarpel">nike air max tn maschio nero bianca rosso</a> <a href="http://www.calsportswear.com/nike-air-max-2017-hommes-bleu-noir-chaussuresh">nike air max 2017 hommes bleu noir</a>
arealleader http://www.arealleader.com/
mariusen
 mariusen 2019-03-16 19:18回复
#117
<a href="http://www.seymourdugan.com/kobe-11-lyser%C3%B8d-skoj">kobe 11 lyser酶d</a> <a href="http://www.dkstekstil.com/nike-foamposite-one-femminile-rosa-scarpeq">nike foamposite one femminile rosa</a> <a href="http://www.thegillssell.com/air-jordan-horizon-purple-yellow-shoesj">air jordan horizon purple yellow</a>
mariusen http://www.mariusen.com/
turisim
 turisim 2019-03-14 20:20回复
#116
<a href="http://www.bgaddiict.com/white-and-black-adidas-ultra-boost-shoesh">white and black adidas ultra boost</a> <a href="http://www.deriogolf.com/nike-cortez-blanc-gorge-vert-chaussuresl">nike cortez blanc gorge vert</a> <a href="http://www.poluscompany.com/womens-nike-sb-stefan-janoski-max-black-grey-shoesj">womens nike sb stefan janoski max black grey</a> <a href="http://www.pariswebjob.com/st-louis-cardinals-trucker-hat-hatk">st louis cardinals trucker hat</a> <a href="http://www.dakvideo.com/light-lyser%C3%B8d-zx-flux-adidas-skoj">light lyser酶d zx flux adidas</a> <a href="http://www.freshkeema.com/lauren-ralph-lauren-womens-two-way-zip-leather-skirt-polo-black-0-poloh">lauren ralph lauren womens two way zip leather skirt polo black 0</a>
turisim http://www.turisim.com/
factorxf
 factorxf 2019-03-14 18:47回复
#115
<a href="http://www.gregertopsoil.com/nfl-nike-new-york-giants-53-connor-barwin-ash-name-number-logo-long-sleeve-t-shirt-nflx">nfl nike new york giants 53 connor barwin ash name number logo long sleeve t shirt</a> <a href="http://www.leatherleif.com/ash-nick-mullens-womens-jersey-4-nike-nfl-one-color-san-francisco-49ers-pullover-hoodie-nflz">ash nick mullens womens jersey 4 nike nfl one color san francisco 49ers pullover hoodie</a> <a href="http://www.marcofabrin.com/billig-kd-trey-5-gr%C3%A5-svart-lilla-kurpesa">billig kd trey 5 gr氓 svart lilla</a> <a href="http://www.napscase.com/adidas-prougeator-keepershandschoenen-fingersave-junior-butyg">adidas prougeator keepershandschoenen fingersave junior</a> <a href="http://www.pcforecasting.com/denver-broncos-john-elway-womens-orange-nike-7-nfl-pullover-hoodie-name-number-logo-nflx">denver broncos john elway womens orange nike 7 nfl pullover hoodie name number logo</a> <a href="http://www.tridenttrump.com/nike-air-max-2016-azul-negro-blanco-butyd">nike air max 2016 azul negro blanco</a>
factorxf http://www.factorxf.com/
genievres
 genievres 2019-03-13 23:03回复
#114
<a href="http://www.truthtapes.com/adidas-springblade-ignite-pink-sky-blue-shoesj">adidas springblade ignite pink sky blue</a> <a href="http://www.veskopetrov.com/air-jordan-super-fly-mintgr%C3%B8n-gr%C3%B8n-skoi">air jordan super fly mintgr酶n gr酶n</a> <a href="http://www.kaosmotogp.com/air-jordan-retro-13-femminile-viola-verde-scarpel">air jordan retro 13 femminile viola verde</a> <a href="http://www.doularhythms.com/nike-free-run-3-womens-yellow-silver-shoesj">nike free run 3 womens yellow silver</a> <a href="http://www.animalpainvet.com/michael-kors-jet-set-wallet-fuschia-mkh">michael kors jet set wallet fuschia</a> <a href="http://www.texarillo.com/nike-roshe-two-flyknit-himmelen-bl%C3%A5-gull-obuvi">nike roshe two flyknit himmelen bl氓 gull</a>
[url=http://www.genievres.com/]genievres[/url]
顶部留言底部
 00:00/00:00
我想和你虚度时光 - 花房姑娘(9)
  1. 我想和你虚度时光
  2. 花房姑娘
  3. 恋恋风尘
  4. 我喜爱一切不彻底的事物
  5. 我的心里是满的
  6. Long Way
  7. 给少年的歌
  8. 晴日共剪窗
  9. 天上的月你的脸