JavaScript Programming Mode

Source: Internet
Author: User

Programming patterns are best-practice scenarios derived from experience and exploration that contribute to readability and maintainability, as well as to improve overall performance.

Behavioral Isolation

General: 22 isolation between structure, style, and behavior.

    • Avoid the use of inline events in structs

    • Try to use fewer <script> labels

    • Consider the case where JavaScript is disabled, add some replacement tags

name Space

To reduce naming conflicts, optimize JavaScript performance, define as few global variables as possible, and define other variables and methods as attributes of these variables.

//定义全局变量var MYAPP = window.MYAPP || {};//定义属性MYAPP.event = {};//定义方法MYAPP.event = {  addListener : function() {    //执行相关的逻辑操作  }  removeListener : function() {    //执行相关的逻辑操作  }  //其他方法};

Use the constructor function in the namespace.

MYAPP.dom = {};MYAPP.dom.Element = function (type, prop) {  var tep = document.createElement(type);  for (var i in prop) {    tmp.setAttribute(i, prop[i]);  }  return tmp;}

Namespace method:

var MYAPP = window.MYAPP || {};MYAPP.namespace = function (name) {  var parts = name.split(“.”);  var current = MYAPP;  for (var i in parts) {    if (!current[parts[i]]) {      current[parts[i]] = {};    }    current = current[parts[i]];  } }MYAPP.namespace(“dom.event”);// 上述操作等价于:var MYAPP = {    dom: {        event: {}    }}
 initialization function

Due to the inconsistency of the browser, we usually do some functional testing before we use JavaScript to manipulate the DOM or BOM. If you need to detect more features before running, it can seriously affect the execution speed of the script. For this problem, it can be solved by the initialization function, that is, after the script is loaded, the function detection of the important function is performed immediately. As a follow-up, there is no need to detect functions and can execute the related functions directly.

var MYAPP = window.MYAPP || {};MYAPP.event = {  addListener: null,  removeListener: null};// 初始化功能演示如下:if (typeof window.addEventListener === ‘function’) {  MYAPP.event.addListener = function (el, type, fn) {    el.addEventListener(type, fn, false);  };  MYAPP.event.removeListener = function (el, type, fn) {    el.removeEventListener(type, fn, false);  };} else if (typeof document.attachEvent === “function”) {  MYAPP.event.addListener = function (el, type, fn) {    el.attachEvent(“on” + type, fn);  };  MYAPP.event.removeListener = function (el, type, fn) {    el.detachEvent(“on” + type, fn);  };} else {  MYAPP.event.addListener = function (el, type, fn) {    el[“on” + type] = fn;  };  MYAPP.event.removeListener = function (el, type, fn) {    el[“on” + type] = null;  }; }
 Delay Definition

The delay definition happens to be the opposite of the idea of initializing the pattern. For those functions that are not necessarily called, you can initialize them when they are called and initialize them only once.

var MYAPP = window.MYAPP || {};MYAPP.event = {  addListener: function(el, type, fn) {    if (typeof window.addEventListener === ‘function’) {      MYAPP.event.addListener = function (el, type, fn) {        el.addEventListener(type, fn, false);      };    } else if (typeof document.attachEvent === “function”) {      MYAPP.event.addListener = function (el, type, fn) {        el.attachEvent(“on” + type, fn);      };    } else {      MYAPP.event.addListener = function (el, type, fn) {        el[“on” + type] = fn;      };    }    MYAPP.event.addListener(el, type, fn);  }};

This place I need to modify, use can rewrite their own functions.

 Configuration Objects

Configures the object pattern for passing multiple arguments to a function. Simply put, the parameter collection is placed in an object, and the object is passed to the parameter, which can even be a JSON file. When the number of parameters is small, it is like a traditional parameter, when the parameter set is large, it is like passing the environment configuration variable. Decoupling variables and functions is a good practice:

    • No need to consider the order of parameters

    • Some parameters can be ignored

    • Better readability and maintainability

var MYAPP = window.MYAPP || {};MYAPP.dom = {};MYAPP.dom.Button = function(text, conf) {    var type = conf.type || “submit”;    var color = conf.color || “red”}// 使用方式var conf = {    type: “reset”,    color: “green”};new MYAPP.dom.Button(“Reset”, conf);
 private variables and methods

Unlike C + + and JAVA, JavaScript does not have modifiers that control access, but we can use local variables and functions to implement similar permission controls.

var MYAPP = window.MYAPP || {};MYAPP.dom = {};MYAPP.dom.Button = function (text, conf) {  var styles = {    color: “black”  }  function setStyles() {    for (var i in styles) {      b.style[i] = conf[i] || styles[i];    }  }  conf = conf || {};  var b = document.createElement(“input”);  b.type = conf[“type”] || “submit”;  b.value = text;  setStyles();  return b;}

Here, it styles is a private property, and it setStyle() is a private method. Constructors can call them internally (they can also access any object in the constructor), but they cannot be called by external code.

 Privileged Functions

In the example above, we can b add a getDefaults() method to return an styles object, which enables access to an internal property or method, which getDefaults() is a privileged function.

 public ownership of private functions

To prevent external modifications, the function is set to private and sometimes externally accessible, so it needs to be public. The solution is to use public variables to refer to private functions to make them public.

var MYAPP = window.MYAPP || {};MYAPP.dom = {};MYAPP.dom.Button = (function () {  var _setStyle = {};  var _getStyle = ();  return {    setStyle: _setStyle,    getStyle: _getStyle,    yetAnother: _setStyle  };  })();
 self-executing functions

Using an anonymous function that executes immediately can also guarantee that the global namespace will not be contaminated. All variables of this function are local and destroyed when the function returns (non-closures).

Ideal for performing one-time initialization tasks.

(function(){    //编写逻辑操作代码})()
 Chained calls

Chained invocation is a convenient way to call. The essence of its implementation is to use a consistent context object and pass this object between chained methods. This flexible invocation style is also a feature of JQuery.

 JSON

JSON is a lightweight format for data interchange. Because it is made up of JavaScript-like objects and array-tagged data, it is very convenient to parse.

Say parsing, we can use JavaScript to eval() convert, but because eval() of its own flaws, this is a more secure approach, such as some JavaScript libraries (http://json.org):

var obj = JSON.parse(xhr.respnseText);





JavaScript Programming Mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.