Namespacing در جاوااسکریپت
می 29, 2008 at 11:01 ب.ظ | In برنامه نویسی/کد نویسی یا توسعه | Leave a Commentهمانطور که میدونید ، جاوا اسکریپت بر خلاف جاوا و سی شارپ ، فاقد ساختار Namespacing هست و در نتیجه وقتی میخوایم اسکریپتی بنویسیم که کمی پیچیده تر از حد یک جاوااسکریپت معمولیه و یا کمی طولانیتره ، کنترل و دیباگ اون کمی مشکله !
امکان دسته بندی ، کنترل و دیباگ سریع که Namespacing به ما میده رو میتونید در جاوا اسکریپتها هم شبیه سازی کنید.برای اینکار کافیه ابتدا یک شی ء پایه بسازید و توابع جاوااسکریپت و کدهاتونو داخل اون شی ء که بنوعی Namespace شما تلقی میشه ، پیاده سازی کنید.مثالی از اینکار رو در زیر می بینید:
// Create the namespace object. Error checking omitted here for brevity.
var myNameSpace;
if (!myNameSpace) myNameSpace = {};
myNameSpace.myPseudoClass = {};
//JavaScript doesn't support classes,
// so let's avoid confusing people and call this a Pseudo Class
// Don't stick anything into the namespace directly.
// Instead we define and invoke an anonymous function to create a closure
// that serves as our private namespace. This function will export its
// public symbols from the closure into the myNameSpace object
// Note that we use an unnamed function so we don't create any other
// global symbols.
(function() { // Begin anonymous function definition
// Nested functions create symbols within the closure
function displayMyMessage() { alert(myMessage); }
// Local variable are symbols within the closure.
// This one will remain private within the closure
var myMessage = 'Hello World';
// This function can refer to the variable with a simple name
// instead of having to qualify it with a namespace
function getMyMessage() { return myMessage; }
// Now that we've defined the properties we want in our private
// closure, we can export the public ones to the public namespace
// and leave the private ones hidden here.
var ns = myNameSpace.myPseudoClass;
ns.displayMyMessage = displayMyMessage;
ns.getMyMessage = getMyMessage;
})(); // End anonymous function definition and invoke it
No Comments Yet »
RSS برای دیدگاههای این نوشته. آدرس دنبالک
دیدگاهتان را بنویسید:
وبلاگ روی وردپرس.کام. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.

گوگل ریدر اشتراکی 