function User(name){ this._name = name } User.prototype.name = function(){ return this._name }The User object shall contain a private variable name. One of the accepted notations is to begin the private variable name with underline character ("_") like "_name".
That still does not make the variable private yet. The HTML:
and some Javascript, which binds the behaviour onto the button:
$(document).ready(function(){ $("#20140615").click(function(event){ var user = new User( $("#20140615_text").val() ) user._name = user._name.split('').reverse().join('') alert(user.name()) }) })Please note, that it is still possible to change the "private" value in _name from outside. Finally the users name is printed for inspect. Examine it:
Refactoring
The original User can be refactored to have a real private variable:function User(name){ this.name = function(){ return name } }with the behaviour attached to the DOM:
$(document).ready(function(){ $("#20140615").click(function(event){ var user = new User( $("#20140615_text").val() ) alert(user.name()) }) })There is no way to modify the value of the name variable.
The concept behind is the oftentimes underrated closure (also read: Have a Javascript closure!). It "freezes" the name variable in the moment, the user object was instantiated.
Please note that using closures for private variables is pretty static, but secure.
Try it:
Further articles of interest:
Supported by jQuery 1.10.2
Keine Kommentare:
Kommentar veröffentlichen