Javascript is weeeell a script-based language. But over the years it has evolved a lot! So can we develop in an Object Oriented Way using javascript? Of course we can! Here is one (of many) way of creating a class in javascript using the prototype method (beware there is also a javascript framework - like jQuery that has the same name)!
Let's create a person class that has two methods (IsHungry,Eat) and two fields (ring any bells?):
Person = function(fullname) { this.fullName = fullname; this.foodQuantity = 0; } Person.prototype = { eat: function() { this.foodQuantity++; alert(this.foodQuantity); }, isHungry: function(){ return true; } };
The we can use our class like any other OO language :
var p = new Person(‘John’); if(p.isHungry()) { p.eat(); }
Although it looks like a class and feels like a class we can’t have private and public members. Everything is public. That means :
p._fullName
is perfectly valid. There is a way of creating classes with true public and private fields but this is something for another post. I also prefer this way despite the public/private flaw.
PS: If there is a way of implementing private fields and methods using the Prototype method please let me know.
Andreas on said
Your example doesn't work.
$1
$1Prototype like this:
$1
$1Person.prototype.eat: function() {
$1 this.foodQuantity++;
$1 alert(this.foodQuantity);
$1};
$1
$1Person.prototype.isHungry: function(){
$1 return true;
$1};
$1
Andreas on said
I meant this:
$1Person.prototype.eat = function() { this.foodQuantity++; alert(this.foodQuantity); }; Person.prototype.isHungry = function(){ return true; };
$1
$1(Forgot to replace the colons with equal signs)
djsolid on said
Problem fixed! Thanks for the notice!