google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Tổ chức mã nguồn JavaScript của bạn tốt hơn Bài viết JavaScript miễn phí này hướng dẫn bạn cách thức để tổ chức mã nguồn JavaScript, ứng dụng web của mình một cách tốt hơn. Vui lòng vào trang chi tiết để xem thêm.


Nhãn: tổ chức, mã nguồn JavaScript, cách thức, ứng dụng web

Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

Javascript is an interesting language because it is flexible and surprisingly powerful. Once you grow up from having one static page into having a large number of pages in a dynamic web application, you need conventions on how to organize your code.

In my opinion, there are two parts to the problem:

  1. the easy part, which is to apply JS programming patterns
  2. the hard part, which is doing so in a consistent and maintainable manner

The easy part: Namespaces, modules and commenting conventions

Namespace and module pattern

Javascript has no explicit syntax for advanced language features such as namespaces and private variables, but these can be implemented using very simple programming patterns.

A lot has been written on the namespace and module pattern, so I will only illustrate it here.

I like to add a "placeholder" function shown below to prevent me from making errors while modifying the module (IE6 freaks out if there is a comma after the last item). This used to happen when I moved or added the methods and forgot to check whether that the commas are correct.

The example code below is adopted from (http://yuiblog.com/blog/2007/06/12/module-pattern/):

// create a namespace
YAHOO.namespace("myProject");
// Assign the return value of an anonymous function to the namespace

/** @namespace */
YAHOO.myProject.myModule = function () {
	/** @private */

	var myPrivateVar = "I can be accessed only from within YAHOO.myProject.myModule.";
 
	/** @private */
	var myPrivateMethod = function () {

		YAHOO.log("I can be accessed only from within YAHOO.myProject.myModule");
	}
 
        /** @scope YAHOO.myProject.myModule */
	return  {

		/** describe myPublicProperty here */
		myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty."
		/** describe myPublicMethod here */
		myPublicMethod: function () {

			YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");
 
			//Within myProject, I can access "private" vars and methods:
			YAHOO.log(myPrivateVar);

			YAHOO.log(myPrivateMethod());
 
			//The native scope of myPublicMethod is myProject; we can
			//access public members using "this":

			YAHOO.log(this.myPublicProperty);
		},
		/**
		* A placeholder function to prevent errors due to not having a comma after the last function in the return statement for this module.
		*/

		placeholder: function () {}
};
 
}(); // the parens here cause the anonymous function to execute and return

Commenting conventions. Pick a commenting tool and stick with it. Comment the intent of the code and any gotchas as well as the expected arguments and purpose of methods.

The two main JavaScript commenting tools are: JsDoc-Toolkit (self-contained Java) and YuiDoc (Python).

File names and splitting code into files. Put all the hard-to-reuse code into its own namespace (ex. Framework. ModuleName. ModulePart.ApplicationName) in a separate file (application.js or custom.js). This way you keep the library clean of any application-specific stuff. It is often hard to avoid implementing some things in a one-off manner, so you might as well organize all the single-use stuff in its own file.

That is, if writing your own extensions to an existing framework, you will most likely have:

  1. code that is fully reusable (specialized or pre-configured widgets, utilities etc.)
  2. code that is hard or pointless to reuse (page- or application-specific messages, formatting and utilities)

The hard part: structuring code for reuse, logical naming conventions

Structuring code for reuse. Encourage reuse by splitting code into configuration, implementation and customization.

  1. Configuration is anything that might need to change on each instantiation of your widget. It should be single section within a module (a private object in JSON notation). Make sure you have good and documented defaults, because this makes it easier to use the code again.
  2. Implementation is the main code. It should NEVER contain hardcoded ID's, messages or other things that will eventually need to be overridden.
  3. Customization is a set of page-specific blocks of code that alter the configuration. You only override the few things that are needed for the specific functionality on the page.

Here is an example (from http://www.wait-till-i.com/2008/05/23/script-configuration/):

myProject.myModule = function(){

// CONFIGURATION
  var config = {
    CSS:{
     classes:{

       hover:'hover',
       active:'current',
       jsEnabled:'js'

     },
     ids:{
       container:'maincontainer'
     }

    },
    timeout:2000,
    userID:'chrisheilmann'
  };

 
  // IMPLEMENTATION
  function init(){ };
  // make init and config public

  return {
    init:init,
    config:config
  };

}();
 
// CUSTOMIZATION
// This makes it possible to override stuff before calling init
module.config.CSS.ids.container = 'header';

module.config.userID = 'alanwhite';
module.init();

Naming conventions. I don't mean deciding whether or not to use camelCase, but rather how the logical organization names of variables and widgets should be done. It is reasonably simple to stop using global variables and functions to avoid name conflicts, but what is harder is to come up with a logical naming convention that allows any code to be reused anywhere.

In particular, when you create new widgets, you often need to be able to connect them to one another in some manner. Being able to identifying the type (class) and retrieve/replace data from a new widget using a standard interface takes some planning and a lot of discipline, but it makes reusing the widgets much easier.

ID and name attribute naming convention. I use "data[widgetName][recordIndex][fieldName]" for input names (because PHP will parse this into arrays automatically) and "widgetName_fieldName_recordIndex" for ID attributes (because it makes string comparisons easier).

Widget instance naming convention. I use YAHOO.ApplicationName.WidgetInstanceName for widget instances, and use WidgetInstanceName to create any related tags with IDs.

I am still looking for a good logical naming convention for widgets, but it seems this topic is not as commonly discussed. If you have any tips, please leave a comment!

Reference stuff

http://stackoverflow.com/questions/211795/are-there-any-coding-standards-for-javascript

http://ajaxian.com/archives/maintainable-javascript-videos-are-now-available

http://yuiblog.com/blog/2007/06/12/module-pattern/

http://www.wait-till-i.com/2008/05/23/script-configuration/

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web