Obiecte in javascript

Metoda clasica de scriere a unui obiect:

function Circle(radius){
this.radius = radius;
this.getArea = function(){
return (this.radius*this.radius*3.14);
}

this.getCircumference = function(){
var diameter = this.radius*2;
var circumference = diameter*3.14;
return circumference;
}
}


Exemplul ilustraza folosirea proprietatilor si metodelor obiectelor.


...............................................

Pentru ca in JavaScript obiectele sunt si vectori asociativi, atunci putem folosi sintaxa:


testObj = {
prop1:"hello",
prop2:"hello2",
prop3:new Array("helloa",1,2)
}

for(x in testObj) alert( x + "-" + testObj[ x ] )


sau folosind jquery:


jQuery.each(testObj, function(key, value) {
console.log("key", key, "value", value);
});



Iata si un exemplu mai complex ce foloseste jQuery si 2 functii utilitare:

$.extend si call

var contactForm = {

container: $('#contact'),

config: {
effect: 'slideToggle',
speed: 500
},

init: function(config) {
$.extend(this.config, config);

$("<button ></ button>", {
text: 'Contact Me'
})
.insertAfter( 'article:first' )
.on( 'click', this.show );
},

show: function() {
var cf = contactForm,
container = cf.container,
config = cf.config;

if ( container.is(':hidden') ) {
contactForm.close.call(container);
container[config.effect](config.speed);
}
},

close: function() {
var $this = $(this), // #contact
config = contactForm.config;

if ( $this.find('span.close').length ) return;

$('X')
.prependTo(this)
.on('click', function() {
// this = span
$this[config.effect](config.speed);
})
}
};

contactForm.init({
// effect: 'fadeToggle',
speed: 300
});



Mai multe detalii:
http://tutsplus.com/lesson/slides-and-structure/