जावास्क्रिप्ट ऑब्जेक्ट वास्तव में अच्छे हैं, लेकिन कभी-कभी वे कुछ उपयोगी छोटे कार्यों / विधियों को याद कर रहे हैं। ऊपर का उदाहरण Arrays के साथ है। यह जानना वास्तव में अच्छा है कि कोई वस्तु आपके सरणी में निहित है या नहीं। वैसे आप एक ऐसा फंक्शन लिख सकते हैं जो आपके द्वारा चेक की जा रही सरणी और आइटम को लेता है, लेकिन इसमें एरे ऑब्जेक्ट में शामिल (आइटम) विधि को जोड़ने के लिए बहुत क्लीनर है।
जावास्क्रिप्ट Arrays का विस्तार
/** * Array.prototype.(method name) allows you to define/overwrite an objects method * needle is the item you are searching for * this is a special variable that refers to "this" instance of an Array. * returns true if needle is in the array, and false otherwise */ Array.prototype.contains = function ( needle ) ( for (i in this) ( if (this(i) == needle) return true; ) return false; )
प्रयोग
// Now you can do things like: var x = Array(); if (x.contains('foo')) ( // do something special )