OOP JavaScript #fast-learn

oop javascript, encapsulation, inheritance, polymorphism

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Fast Learn OOP js</title>
</head>

<body>

<script type="text/javascript">

function Area(){

 // local or private variable (encapsulation)
 var pi = 3.14;

 // public variable (encapsulation)
 this.width     = 3;
 this.radius    = 4;

 // get square area
  this.square = function(){
   return this.width * this.width;
  }

 // set width value
  this.setWidth = function(w){
    this.width = w;
 }

// get circle area
 this.circle = function(){
    return pi * this.radius * this.radius;
 }

// set radius value
  this.setRadius = function(r){
   this.radius = r;
  }
};

// test Area class
var luas = new Area();
luas.setWidth(5);
console.log(luas.square());
luas.setRadius(3);
console.log(luas.circle());

// create our area class
function MyArea(){};

// Inheritance from area class
MyArea.prototype = new Area();

// binding square function, upgrade to accept width value (polymorphism ?)
MyArea.prototype.square = function(w){
  //console.log('MyArea.prototype.square');
  if(w) this.width = w;
  return this.width * this.width;
}

// test our new class
var myluas = new MyArea();
console.log(myluas.square());
console.log(myluas.square(4));
console.log(myluas.width);

</script>
</body>
</html>

more resource
http://www.techumber.com/2013/08/javascript-object-oriented-programming-tutorial.html
http://stackoverflow.com/questions/9850892/should-i-use-polymorphism-in-javascript
http://www.codeproject.com/Articles/315169/Polymorphism-in-JavaScript

Published by

G3n1k

just to remember what i had known :)

One thought on “OOP JavaScript #fast-learn”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s