How can I create an empty namespace object without overwriting another object with the same name?

前端 未结 3 1617
南旧
南旧 2021-01-23 10:51

I have been studying as much as I can about the Module Pattern suggested by the Yahoo YUI Blog.

I\'ve noticed that the YUI offers the ability to create a new empty names

3条回答
  •  庸人自扰
    2021-01-23 11:32

    Q. How can I create an empty namespace object without overwriting another object with the same name?

    You can't. By definition the same name can't refer to both your new empty object and an existing object.

    If you mean "How can I check create an empty namespace object only if it doesn't already exist, otherwise I want to add to the existing one", then you just do this:

    if (!YAHOO.myProject)
       YAHOO.myProject = {};
    
    // or you may see this variation:
    YAHOO.myProject = YAHOO.myProject || {};
    

    I don't like the latter but it is used frequently to achieve the same effect as a plain if statement.

    To take this general principle much further have a look at this article: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

    UPDATE: According to the YUI API documentation for YAHOO.namespace(), the method "Returns the namespace specified and creates it if it doesn't exist" - which you'll note is much less ambiguous than the wording of the blog you were reading, and pretty much backs up what I already said...

提交回复
热议问题