Home > Web Front-end > JS Tutorial > javascript namespaces to improve code reusability_javascript tips

javascript namespaces to improve code reusability_javascript tips

WBOY
Release: 2016-05-16 18:58:54
Original
1283 people have browsed it

When more than 10 js files are introduced into the same web page,
functions with the same name in each js can easily conflict.
For example, the addCssStyle method is written in the xxx library, and the addCssStyle method is also written in the yyy class library.
There are certain differences in the specific implementation of these two methods.
When these two components are referenced at the same time, the function conflict will cause the page effect to change.
Debugging and modification are very painful. If in order to avoid conflicts,
give up referencing some excellent components, That is even more depressing.

For this reason, when encapsulating JavaScript component libraries, please use namespaces to avoid conflicts.
Write all methods and variables according to the package name and class name.
(Writing code at this time feels as convenient as encapsulating java's util method, haha)
From this, my js library is encapsulated as follows.
I googled for a long time, but there was nothing ready-made, so I figured it out by myself. The sample code is as follows:
(lizongbo original!!!)




Put the above code Copy it on the web page and see the effect.
Comparing the two implementation methods, it is most convenient to transform the existing code in the second method.
Rename the js file according to the namespace, which will make the operation more convenient.
For example


As long as libraries are written in this way, you no longer have to worry about function conflicts after introducing multiple js files.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template