برای هر پروژه ای نیاز به تعریف class وجود دارد. روشهای مختلفی برای تعریف وجود دارد که چند موردش عبارت است از:
استفاده از function
یکی از معمول ترین روش هاست. در این حالت شما یک function تعریف میکنید و موارد را در context همان اضافه می کنید.
function Apple (type) { this.type = type; this.color = \"red\"; this.getInfo = getAppleInfo; } // anti-pattern! keep reading... function getAppleInfo() { return this.color + \' \' + this.type + \' apple\'; }
شما می تونید با استفاده از new یک instance جدید ایجاد کنید.
var apple = new Apple(\'macintosh\'); apple.color = \"reddish\"; alert(apple.getInfo());
شما میتوانید متد های مرتبط را به صورت داخلی تعریف کنید.
function Apple (type) { this.type = type; this.color = \"red\"; this.getInfo = function() { return this.color + \' \' + this.type + \' apple\'; }; }
یا اینکه از protoype استفاده کنید.
Apple.prototype.getInfo = function() { return this.color + \' \' + this.type + \' apple\'; };
به طور کلی تعاریف دیگر OOP را هم میتوانید در این تعریفها پیادهسازی کنید.
به طور مثال پیادهسازی مربوط به ارث بری را ببیند.
pear.prototype = new Apple;
استفاده از Object
در javascript دیکشنری ها object هستند و شما به راحتی میتوانید یک object جدید درست کنید.
var o = {};
یا اینکه از object یک instance جدید بسازید.
var o = new Object();
حالا با استفاده از این ساختار شما میتوانید یک کلاس بسازید
var apple = { type: \"macintosh\", color: \"red\", getInfo: function () { return this.color + \' \' + this.type + \' apple\'; } }
و به راحتی ازش استفاده کنید.
apple.color = \"reddish\"; alert(apple.getInfo());
استفاده از کلاسهای آماده
کلاً مسأله class در javascript اینقدر جدی بوده که کلاسهای زیادی برای کار با آن نوشته شده است.
- k33g/speculoos -> https://github.com/k33g/speculoos
- ded/klass -> https://github.com/ded/klass
- Classy Classes for JavaScript -> http://classy.pocoo.org/
- jsclassextend - JS Class is small and powerfull library which simplifies oop in javascript - Google Project Hosting -> http://code.google.com/p/jsclassextend/
- jayferd/pjs -> https://github.com/jayferd/pjs
- jiem/my-class -> https://github.com/jiem/my-class
- ShadowCloud/ES5-Class -> https://github.com/ShadowCloud/ES5-Class
- gigafied/minion -> https://github.com/gigafied/minion
- jasonwyatt/ancestry.js -> https://github.com/jasonwyatt/ancestry.js
- JS.Class v3.0 -> http://jsclass.jcoglan.com/
- tekool/objs -> https://github.com/tekool/objs
- maccman/superapp -> https://github.com/maccman/superapp
همچنین ببینید
-
ways to define a JavaScript class / Stoyan\'s phpied.com -> http://www.phpied.com/3-ways-to-define-a-javascript-class/