0

下面是一个小 JavaScript 项目,用于在网页上显示引号。因为我想在许多不同的网站上使用它,所以我阅读了制作可移植 JavaScript 代码的良好实践,例如:

  • 不使用全局变量
  • 使用命名空间
  • 让插件变得容易
  • 使用可以被覆盖的默认值

对于那些有编写 JavaScript 库和可移植 JavaScript 代码经验的人,可以对这段代码进行哪些改进,以 (a) 使其更便携,(b) 避免任何不可预见的问题或冲突,(c) 改进命名约定等.?

索引.htm:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>smart quotes</title>
        <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
        <script type="text/javascript" src="js/smartquotes.js"></script>
        <script type="text/javascript">
            window.onload = function() {
                SMARTQUOTES.init();
                SMARTQUOTES.quotes = new Array(
                'It\'s tempting to augment prototypes of built-in constructors such as Object(), Array(), or Function(), but it can seriously hurt maintainability.',
                'We come from XHTML backgrounds, so we will close all tags, use lowercase, and use quotation marks around attributes.',
                'Checking to see if a value exists inside an array is always a bore in JavaScript.',
                'JavaScript classes have the same effect on some people that garlic has on Dracula.',
                'Mixins are not supported natively by CoffeeScript, for the good reason that they can be trivially implemented yourself.',
                'Using a single var statement at the top of your functions is a useful pattern to adopt.',
                'Using the Function() constructor is as bad as eval()',
                'Any obstacle that I\'ve encountered during my development by placing JavaScript at the bottom of the page has been easily overcome and well worth the optimization gains.'
                );
                SMARTQUOTES.duration = 8000;
                SMARTQUOTES.start();
            };
        </script>
        <style type="text/css">
            div#quoteWrapper {
                border: 1px solid #999;
                padding: 10px;
                background: #eee;
                color: navy;
                width: 300px;
                border-radius: 5px;
                font-style: italic;
                font-family: arial;
                font-size: 12pt;
                text-align: center;
            }

        </style>
    </head>
<body>
    <div id="quoteWrapper">
        <div id="SMARTQUOTE"></div>
    </div>
</body>

smartquotes.js:

(function(global) {
    var SMARTQUOTES = {};
    if(global.SMARTQUOTES) {
        throw new Error('SMARTQUOTES has already been defined');
    } else {
        global.SMARTQUOTES = SMARTQUOTES;
    }
})(typeof window === 'undefined' ? this : window);  

SMARTQUOTES.init = function() {
    SMARTQUOTES.quoteIndex = 0;

    SMARTQUOTES.duration = 3000;

    SMARTQUOTES.quotes = new Array();
    SMARTQUOTES.quotes[0] = 'test quote #1';
    SMARTQUOTES.quotes[1] = 'this is the second quote';
    SMARTQUOTES.quotes[2] = 'and now the third and last quote'; 

    SMARTQUOTES.element = $('div#SMARTQUOTE').hide();

    SMARTQUOTES.incrementQuote = function() {
        SMARTQUOTES.quoteIndex++;
        if(SMARTQUOTES.quoteIndex >= SMARTQUOTES.quotes.length) {
            SMARTQUOTES.quoteIndex = 0;
        }
    }

    SMARTQUOTES.displayQuote = function () {
        var quote = SMARTQUOTES.quotes[SMARTQUOTES.quoteIndex];
        SMARTQUOTES.element.fadeOut('slow', function() {
            SMARTQUOTES.element.html(quote);
        });
        SMARTQUOTES.element.fadeIn();
        SMARTQUOTES.incrementQuote();
        SMARTQUOTES.startTimer();
    }

    SMARTQUOTES.startTimer = function () {
        var t = setTimeout('SMARTQUOTES.displayQuote()', SMARTQUOTES.duration);
    }

    SMARTQUOTES.start = function() {
        SMARTQUOTES.displayQuote();
    }

}
4

1 回答 1

1

Few ideas (I'll add more later):

  • You could replace the first part (global) with a

var SMARTQUOTES = SMARTQUOTES || {};

  • You could add an optional "element" in your init. Something like:
SQ.init = function (elem) {     
  if (elem === undefined) {     
    elem = 'div#SMARTQUOTE';     
  }     
  // ...     
  SQ.element = $(elem).hide();     
  // ...
  • Maybe enclose it all in a self-executing block:
(function (){
  var SMARTQUOTES = SMARTQUOTES || {};
  SMARTQUOTES.init = function (elem) {
  ...
  }
}());
  • Even better, use this keyword
(function (){
  var SMARTQUOTES = SMARTQUOTES || {};
  SMARTQUOTES.prototype.init = function (elem) {
     var that = this;
     that.index = ...
  ...
  }
  SMARTQUOTES.prototype.displayQuote = function() {
     that.startTimer(); ...
  }
}());
  • Read this and this article. They are about module patterns.
于 2012-05-24T10:57:49.673 回答