29
04
2009

Snippet javascript : Programmation objet

Juste un petit rappel personnel sur comment bien faire un objet en javascript.


function someClass () {
	var _sPrivateVar = '';
	this._sPublicVar = '';

	function privateFunction () {
		return;
	}

	this.publicFunction = function () {
		return;
	}
}

// Add a static function :
someClass.someStaticFunc = function () {
	// Do something static here
}

// Add a new dynamique function into the someClass class :
someClass.prototype.newDynFunc = function () {
	// Do something dynamic here
	// You can access this like if you were into the class !
}

et en bonus, comment bien faire un plugin javascript avec possibilité d'étendre des fonctions du plugin:


// A plugin callable with $.plugin
;(function($) {$.plugin = function () {
	// Code goes here
	return this; // Enable chain functionnality like JQuery do
}})(jQuery);

// A plugin callable with $(DomElt).plugin, with DOMElt is some DOM element
;(function($) {$.fn.plugin = function () {
	// Code goes here
	return this; // Enable chain functionnality like JQuery do
}})(jQuery);

// Adding some functions for the plugin, accessible by $.plugin.doSth ()
$.extend($.plugin, {
	doSth: function () {
		// Do whatever you want
	},
});
// It works the same with $.extend($.fn.plugin, {}) for $(DOMElt).plugin.sth ()

Les bases de la poo en javascipt sont très bien expliquée ici

Share/Save/Bookmark

1 Comment so far ...


  1. Pierre

    Pierre says:

    Apr. 30, 2009, 05:59 AM

    Bookmarked ! Thanks a lot !

Add a comment