The very basic of Object-Oriented Programming (OOP) is private fields and public methods (not considering features like polymorphism, inheritance, etc). So how to achieve this very basic of OOP in JavaScript. It turns out to be easy. Here is how to have private fields in your custom JavaScript functions/classes and using methods of your function/class to amend it.
function User() { var name = ''; return { setName: function(newName) { name = newName; }, getName: function() { return name; } } } var user = User(); user.setName("My Name"); user.getName(); // My Name
The User() class we just created could be considered a bean in Java. Using this template you can have as many private fields and public methods as you want.
Hmm, interesting. I've never seen anyone do that before.
ReplyDeleteI was plesantly surprised to see...
var user = User();
user.setName("My Name");
user.getName(); //My Name
user.name = "Your Name";
user.getName();
to only show "My Name" and not "Your Name"!
Thanks for the tip!
Prototype's version -)
ReplyDeletevar User = Class.create();
User.prototype =
{
initialize: function()
{
// it's our constructor
},
setName: function(name)
{
this.name=name;
},
getName: function()
{
return this.name;
}
}