هنوز چند بایت مونده که پیدا کنم...

نوشتن جاوا اسکریپت به صورت شی گراء

یه نمونه کد برای اونایی که هنوز کدای جاوا اسکریپت شون رو شلخته مینویسن اما میخوان خوانایی بیشتری به کداشون بدن. یه مثال ساده که چطور کدای جاوا اسکریپت رو سازماندهی کنیم.
// Global Variables
var windowWidth;

// Class definition
var App = function() {
    // App variables 
    var app = this;
    var debug = true; 

    this.init = function() {
        windowWidth = app.getWindowWidth();
    };

    // a simple logger
    this.log = function(data) {
        if(window.console && debug) {
            console.log(data);
        }
    };

    // Example of a dummy method
    this.getWindowWidth = function() {
        return $(window).width();
    };

    // Example of a dummy method with arguments
    this.animateImage = function(selector, positionX, duration) {
        selector.animate({'margin-left': '+='+ positionX +'px'}, duration);
    };

    // Example of a private dummy method
    var whatIsPI = function() {
        return Math.PI;
    };
};

// Instantiate the App class
var app = new App();

// Call the init method
app.init();

// Call public methods with arguments
app.animateImage($('.animated-image'), 400, 1200);

app.log('This is shown is the console');

// This will fail as we are trying to call a private method
app.log(app.whatIsPI());

نکته

Object-Oriented JavaScript
نویسنده : محمد ملک مکان
دوشنبه 25 آبان 1394
+ 80 -

ایده ها، نظرات و سوالات دوستان ما

مهمون کدجیک
دوشنبه 6 دی 1395
یه آکولاد کم داره!
+ 10 -
مهمون کدجیک
یکشنبه 23 اسفند 1394
خیلی خوب بود! ممنون
+ 10 -

خوشحال میشیم نظرتُ بدونیم