如何在JavaScript中为命名空间提供实例对象 [英] How to provide namespaces in JavaScript with instanced objects

查看:55
本文介绍了如何在JavaScript中为命名空间提供实例对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript对象",它是通过以下方式构建的:

I've got a JavaScript "object", built this way:

function foo()
{
    this.length = 0;
}

foo.prototype.getLength = function()
{
    return this.length;
}

...

我知道如何使用单例JavaScript对象模拟名称空间,但是命名"对象(例如上面提到的对象)的最佳方法是什么?

I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced?

我知道几个JavaScript库都具有命名空间功能,但是我使用的是jQuery,并且宁愿不添加其他库.我希望能够通过使用jQuery为需要实例化的我的JS对象提供内部命名间隔方案来提供自己的名称.

I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced.

谢谢 rp

推荐答案

简单:

if(!MyNamespace) MyNamespace = {};

MyNamespace.foo = function() {
   this.length = 0;
};
MyNamespace.foo.prototype.getLength = function() {
   return this.length;
};

这篇关于如何在JavaScript中为命名空间提供实例对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆