2013年12月30日 星期一

Javascript OOP


現在的 Javascript 跟我所認識的已經發展出很多的不同,物件導向 OOP 就是其中之一。今天寫了個簡單的程式,以了解它的寫法:
var _heartArray = new Array();

function initObjects()  {
    var windowDiv = document.getElementById("window");
    var centerX = (window.innerWidth/2);
    var centerY = (windowDiv.offsetHeight/2)+100;
    var radius = 180;

    //  Reset icon position
    var elementArray = document.getElementsByClassName("imageDiv");
    var count = elementArray.length;
    var increase = (Math.PI*2)/count;
    var x = 0, y = 0, degree = 0;
    for (var i=0; i<count; i++)  {

        var element = elementArray[i];
        var heart = new Heart(element, centerX, centerY, radius, degree, (Math.PI*2)/176);
        heart.execute();
        _heartArray[i] = heart;

        degree += increase;
    }
    setInterval(runOnce, 1000/60);
}

function runOnce()  {
    var count = _heartArray.length;
    for (var i=0; i<count; i++)  {

        var heart = _heartArray[i];
        heart.execute();
    }
}

function Heart(element, centerX, centerY, radius, degree, stepDegree)  {
    this.element = element;
    this.centerX = centerX;
    this.centerY = centerY;
    this.radius = radius;
    this.degree = degree;
    this.stepDegree = stepDegree;

    this.execute = function()  {
        var iconWidthHalf = 64;
        var iconHeightHalf = 64;

        //  6.2831853 = 360 x radian
        this.degree = this.degree+this.stepDegree;
        if (this.degree > 6.2831853)  {this.degree -= 6.2831853;}
        if (this.degree < 0.0)  {this.degree += 6.2831853;}

        var x = (this.radius*Math.cos(this.degree))+this.centerX-iconWidthHalf;
        var y = (this.radius*Math.sin(this.degree))+this.centerY-iconHeightHalf;

        this.element.style.position = "absolute";
        this.element.style.left = x+"px";
        this.element.style.top = y+"px";
    };
}

沒有留言: