Skip to content
This repository has been archived by the owner on Oct 13, 2023. It is now read-only.

Code Guides Javascript

tobuto edited this page May 19, 2015 · 3 revisions

Namen

Variablen und Funktionen -> camelCase:

var dismissButton;
function setHeader();

Variablen bezogen auf jQuery -> $ als Prefix:

var $dismissButton = $('#dismiss-button');

IDs und Classes -> Kleinbuchstaben mit "-" verbunden:

<div id="my-div" class="green-div">

Codestruktur (JavaScript)

Allgemeines

KEIN

location.reload();

Eventhandler:

$('#element').on('event', function (){
    //do something
});

oder

var $element = $('#element');
$element.on('event', function (){
    //...
});

Objekte/Arrays:

var myObject = {};
//nicht:
var myObject = new Object;

var myArray = [];
//nicht:
var myArray = new Array;
$.each(myObject, function (key, value){
    //...
});

myArray.forEach(function (element, index){
    //...
});

//nicht:
for(i=0; i < myArray.length; i++){
    //...
}

Code Beispiele

Modul:

var globalVariable;

var moduleName = (function (){
    var string1 = 'abc',
        string2 = 'def',
        int1 = 51550;

    var init = function (){
        //initialize things
        globalVariable = 42;
    }

    var myFunction = function (parameter1, parameter2){
        //do something
    }

    var publicFunction = function (parameter1, parameter2, parmeter3){
        //do something
    }

    //public functions:
    return {
        init,
        publicFunction,
    }

})();

//document ready:
$(function (){
    moduleName.init();
});

Klasse:

var Attribute = function(name, standardValue) {
    this.value = 0;
    this.name = name;
    this.changeValue(standardValue);
};

Attribute.prototype = {
    changeValue: function (int){
        if(isNaN(int)){
            this.value = int;
        }else{
            this.value += parseInt(int);  
        }
    }
};
Clone this wiki locally