OOP example

implemented inheritance

by Zevan

HTML

<div id="out">Hello</div>
<canvas id="canvas" width = "500" height = "500" />

CSS

#out{
  position: absolute;
  top: 600px;   
}

JavaScript

Function.prototype.copyProps = function(subclass, superclass){
    for(var key in superclass){
      subclass[key] = superclass[key];   
    }
    for (key in superclass.prototype){
      subclass.prototype[key] = superclass.prototype[key];   
    }
}
Function.prototype.inherits = function(SuperClass, subclass, args){
  this.copyProps(subclass, SuperClass.apply(null,args));
  this.copyProps(this, SuperClass);
}
   
function Main(){
  this.ctx = document.getElementById("canvas").getContext("2d");
  this.ctx.fillStyle = "black";
  this.ctx.fillRect(0,0,500,500);
  
  var ball = new Ball(this.ctx, 200, 200, 20);
}

var main = new Main();


    function dist(x1, y1, x2, y2){
      var dx = x1 - x2;
      var dy = y1 - y2;
      return Math.sqrt(dx * dx + dy * dy);
    }  

function Ball(ctx, x, y, radius){
    //alert(ctx);
    ctx.fillStyle = "red";
    circle(x, y, radius);
    alert(dist(0, 0, x, y));
    
    $("#canvas").mousemove(function(e){
        if (dist(e.offsetX, e.offsetY, x, y) < radius){
          ctx.fillStyle = "white";
          circle(x, y, radius);  
        }else{
          ctx.fillStyle = "red";
          circle(x, y, radius);  
        }
    }, false);
    
    function circle(x, y, radius){
       //alert(ctx);
      ctx.beginPath();
      ctx.arc(x, y, radius, Math.PI * 2, 0, true);
      ctx.closePath();
      ctx.fill();
    }
}




    
    /*
function Ball(a, b, c){
  alert([a, b, c]);
  //alert(this);
  // static
  Ball.x = 1;
  // public
  this.x = 100;
  this.y = 100;
  // private 
  var data = "hello";
  return this;
}

var a = new Ball();
a.x = 200;
a.y = 200;

var b = new Ball();
b.x = 50;
b.y = 50;

//alert([a.x, b.x, Ball.x]);

function RedBall(){
   RedBall.inherits(Ball, this, arguments);
   return this;
}
var red = new RedBall(1,2,3);
alert([RedBall.x, red.x]);*/