Javascript编程模式,JavaScript Programming PatternsPart 1.

JavaScript 为网站添加状态,这些状态可能是校验或者更复杂的行为像拖拽终止功能或者是异步的请求webserver (aka Ajax). 在过去的那些年里, JavaScript libraries变得越来越流行. 如果你面对着很多的工作计划,一个很明确的道理就是在网站变得越来越复杂的情况下每次修改‘轮子“肯定让你不爽.当然我们把类库放到一边,聚焦于 JavaScript的语法,对你最有价值的东西是在你编写 JavaScript你要明确你使用的是那种”编程模式“.

下面主要介绍几个javascript编程模式:

  1. 老式的编程模式(The Old-School Way)
  2. 单例编程模式(Singleton)
  3. 模块编程模式(Module Pattern)

我们会用不同模式解决一个相同的编程任务. 任务如下: 你有3条链接当你点击链接时链接的颜色会变成你预配置的值, 提供的html标签如下:

<ul>

<li><a href="http://news.bbc.co.uk/">News on BBC website</a></li>

<li><a href="http://nytimes.com/">Frontpage of The New York Times</a></li>

<li><a href="http://www.guardian.co.uk/">Guardian Unlimited</a></li>

</ul>

解决以上的编程任务,你需要清楚以下步骤:

  • 定义背景颜色在某些变量里
  • 在上下文获取”锚点“并且保存在数组数据结构中
  • 在一个函数中,循环数组并且粘贴上 onclick 事件来改变背景颜色:
  • 如果链接被点击函数执行背景颜色改变

老式的编程模式(The Old-School Way)

我以一个demo作为说明90年代后2000年代初的javascript如何编程.在那时JavaScript还是纯粹的连续性编程, 定义一个 function 在另外一个function之后. 没人担心命名空间” namespace“. 没人在意可复用的代码.没人在大体上在意,这些脚本是不是要花大价钱进行维护. 他们不为这些事情操心.如果你写过直线编程那么解决以上的任务你只需要 2 functions:

  • anchorChange1: 抓取页面上的链接并且把链接粘贴上click事件
  • changeColor1:执行背景颜色的改变

废话少说, 你将得到以下类似代码:

    // ancient technology
        function changeColor1(linkObj, newColor) {
            linkObj.style.backgroundColor = newColor;
        }

        function anchorChange1() {
            // set configuration
            var config = {
                colors: [ "#F63", "#CC0", "#CFF" ]
            };

            // get all links on page
            var anchors = document.getElementsByTagName("a");
            var size = anchors.length;

            // loop through anchors and attach events
            for (var i = 0; i &lt; size; i++) {
                anchors[i].color = config.colors[i];

                anchors[i].onclick = function () {
                    changeColor1(this, this.color);
                    return false;
                };
            }
        }

在页面贴近结束的body标签处,你需要添加JavaScript 块,即回调的主函数(注意:是结束的body标签处。这和浏览器的解析顺序有关,太往前浏览器不会解析到回调的主函数)

<script type="text/javascript">
    anchorChange1();
</script>

虽然代码的运行效果不错,但是在命名空间上缺乏考虑. 这意味着在许多开发者在一个项目中协同合作时,会出现大问题。如果某人在代码中添加了如下如下function:

 function changeColor1() {
        alert("oh noes, my code got overwritten!");
    }

如果在你定义的 changeColor1 后面又定义了 changeColor1, 你的代码将被同名的方法重写. 如上所述,一个用5到10年的网站经过无数的前端开发者会变得越来越复杂.所以,重写别人的代码是一个潜在的危险.垒代码查找问题简直就是一个噩梦.所以,我相信有技术可以避免它.

单例编程模式(Singleton)

第二种解决方案是我们创建一个单例( singleton0,这意味着创建对象并为对象的 properties 赋值.这种对象创建出来能立即使用,语法如下:

var testObject = {};
开始, 创建一个空的单例:
anchorChange2 = {};
我决定为这个对象创建3个不同的 properties :
  • config: 持有不同的背景颜色
  • alterColor:改变颜色的方法
  • init: 为链接元素附加上变色功能

config属性持有新的背景颜色:

 config: {
        colors: [ "#F63", "#CC0", "#CFF" ]
    }

alterColor属性改变背景颜色:

alterColor: function (linkObj, newColor) {
        linkObj.style.backgroundColor = newColor;
    }

init负责链接在触发onclick事件时调用 alterColor 方法:

 init: function () {
        var self = this; // assign reference to current object to "self"
        var anchors = document.getElementsByTagName("a");
        var size = anchors.length;
        for (var i = 0; i < size; i++) {
            anchors[i].color = self.config.colors[i];
            anchors[i].onclick = function () {
                self.alterColor(this, this.color);
                // this is bound to the anchor object 
                return false;
            };
        }
    }

单例模式代码如下:

  // singleton syntax
        // creates a class and immediately instantiates an object
        var anchorChange2 = {
            config: {
                colors: [ "#F63", "#CC0", "#CFF" ]
            },

            // does the actual change of the background color
            alterColor: function (linkObj, newColor) {
                linkObj.style.backgroundColor = newColor;
            },

            init: function () {
                var self = this; // assign reference to current object to "self"

                // get all links on the page
                var anchors = document.getElementsByTagName("a");
                var size = anchors.length;

                for (var i = 0; i < size; i++) {
                    anchors[i].color = self.config.colors[i];

                    anchors[i].onclick = function () {
                        self.alterColor(this, this.color); // this is bound to the anchor object
                        return false;
                    };
                }
            }
        };

模块编程模式(Module Pattern)

在单例模式之后指引我们的是 Douglas Crockford 提出的 “module pattern”模块模式. 这种思想来自于封闭的模块, 你和别的某块在创建以后不冲突. 你可以在你的模块里面创建

public 或者 private的方法.

首先,让创建一个模块.(即创建一个function,但是结尾处有()):

anchorChange3 = function () {}();
综上所述,使用这种编程模式 可以创建 public 与 private 方法. Public方法可以被外部访问, private方法仅仅在对象内部调用.我们设计一个私有化变量 config,私有化方法 alterColor,再写两个公共的方法一个 color change改变颜色,另一个init方法确定对象实例化的边界. 接下来, 你会得到一个对象并且这个对象有不同的属性:
  return {
            // public method
            // can be accessed from outside
            changeColor: function (linkObj, newColor) {
                // calls private function to change color
                alterColor(linkObj, newColor);
            },
                        
            // public method
            // can be accessed from outside
            init: function () {
                var self = this; // assign reference to current object to "self"
            
                // get all links on the page
                var anchors = document.getElementsByTagName("a");
                var size = anchors.length;
                
                for (var i = 0; i < size; i++) {
                    anchors[i].color = config.colors[i];
                    
                    anchors[i].onclick = function () {
                        self.changeColor(this, this.color); // this is bound to the anchor object
                        return false;
                    };
                }
            }
        };

alterColor函数与config变量在父函数内部,return值得外部:

    var config = {
          colors: [ "#F63", "#CC0", "#CFF" ]
    }
function alterColor(linkObj, color) { linkObj.style.backgroundColor = color; }



alterColor作为私有方法不可以被是外部访问. 在对象内部执行 function (像使用单例模式那样),或者在返回对象的内部创建一个新的属性( property)在执行使用回调方法的时候.稍后将changeColor 改名为 alterColor.

   var anchorChange3 = function () {
        // private property
        var config = { colors: [ "#F63", "#CC0", "#CFF" ] }
        // this is a private method
        // can be accessed within anchorChange3
        // cannot be accessed from outside
        function alterColor(linkObj, color) {
            linkObj.style.backgroundColor = color;
        }

        return {
            // public method
            // can be accessed from outside
            changeColor: function (linkObj, newColor) {
                // calls private function to change color
                alterColor(linkObj, newColor);
            },
            // public method
            // can be accessed from outside
            init: function () {
                var self = this;
                // assign reference to current object to "self"
                // get all links on the page
                var anchors = document.getElementsByTagName("a");
                var size = anchors.length;
                for (var i = 0; i < size; i++) {
                    anchors[i].color = config.colors[i];
                    anchors[i].onclick = function () {
                        self.changeColor(this, this.color);
                        // this is bound to the anchor object
                        return false;
                    };
                }
            } };
    }();

与上面单例模式类似, 在 HTML 中初始化:

<script type="text/javascript">
    anchorChange3.init();
</script>