A Simple Example About Privileged Methods in JavaScript
function FootballPlayer(){}; // declare a function FootballPlayer.prototype.kick = function(){ alert("kick!"); }; // create a public method kick in .prototype var Messi = new FootballPlayer(); Messi.kick();
From my previous article, you have learnt that FootballPlayer.prototype is an object that is built automatically when the function is created. Object constructed with the FootballPlayer, Messi, search through his __proto__ chain when we tell him to kick. Obviously FootballPlayer.prototype is on the chain so Messi knows how to kick. All objects created by the constructor function share the same FootballPlayer.prototype so they all can invoke the public method kick!
function man() { var wealth; var bath = function(){}; function kiss(){} }
In this case, none of wealth, bath or kiss are accessible outsite the function man. Even man‘s public methods cannot access them.
var func = function(a,b) { this.a = a; this.getB = function(){return b}; // a privileged method this.setB = function(n){b=n;}; // another privileged method var b = b; }; func.prototype.getB2 = function(){return b*2}; // public method var obj = new func(1,2); alert(obj.getB()); // privileged method can access private b alert(obj.getB2()); // error: public method cannot access private b obj.setB(11); alert(obj.getB());
So actually we can create privileged methods easily by using the keyword this!
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。