Java-esque OOP in JavaScript and a jQuery fail

前端 未结 6 1662
走了就别回头了
走了就别回头了 2021-02-08 06:31

I\'m working on a project and I\'m really trying to write object-oriented JavaScript code. I have just started reading Douglas Crockford\'s JavaScript: The Good Parts and I\'m q

6条回答
  •  一个人的身影
    2021-02-08 07:14

    If you are developing a plug-in, it is generally best to avoid contaminating both the jQuery and Global namespaces/prototypes as much as possible.

    Have a look at this documentation on jQuery's website, which gives an excellent explanation of how to provide access to a variety of reusable functionality, while only claiming a single name on the jQuery object.

    Another method I have seen used is to provide a single init function for your plug-in on the jQuery namespace, and then make an additional plug-in specific name available in the Global namespace, which provides more direct access to function/members, etc. The Galleria plug-in is an excellent example of how to do this well. Examine their documentation, and the way they set up the structure of the plug-in.

    EDIT

    After seeing that you are not making a plug-in: Many of the things that I said still apply to general jQuery development (and really, to development in general).

    In your specific case, since you are not making use of the jQuery selectors in making your function calls, these functions could probably be just as easily attached to a prototype of your own making, which could be placed in the Global namespace.

    As far as namespacing goes, have a look at the accepted answer on this question for an example of how to do it properly: How do I declare a namespace in JavaScript?

    And here is a great resource for OO in JavaScript. I used this article when trying to wrap my head around the concept: http://mckoss.com/jscript/object.htm

提交回复
热议问题