如何改进此JavaScript代码以使其更具可移植性?

时间:2012-05-24 10:49:25

标签: javascript portability

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

  • 不使用全局变量
  • 使用名称空间
  • 轻松插入
  • 使用可以覆盖的默认值

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

的index.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();
    }

}

1 个答案:

答案 0 :(得分:1)

很少有想法(我稍后会添加更多):

  • 您可以用
  • 替换第一部分(全局)
  

var SMARTQUOTES = SMARTQUOTES || {};

  • 您可以在init中添加可选的“元素”。类似的东西:
SQ.init = function (elem) {     
  if (elem === undefined) {     
    elem = 'div#SMARTQUOTE';     
  }     
  // ...     
  SQ.element = $(elem).hide();     
  // ...
  • 也许将它全部包含在一个自动执行的块中:
(function (){
  var SMARTQUOTES = SMARTQUOTES || {};
  SMARTQUOTES.init = function (elem) {
  ...
  }
}());
  • 更好的是,请使用此关键字
(function (){
  var SMARTQUOTES = SMARTQUOTES || {};
  SMARTQUOTES.prototype.init = function (elem) {
     var that = this;
     that.index = ...
  ...
  }
  SMARTQUOTES.prototype.displayQuote = function() {
     that.startTimer(); ...
  }
}());
  • 阅读thisthis文章。 它们与模块模式有关。