【问题标题】:How to improve this JavaScript code to make it more portable?如何改进此 JavaScript 代码以使其更具可移植性?
【发布时间】:2012-05-24 19:17:10
【问题描述】:

以下是一个在网页上显示引号的小 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();
    }

}

【问题讨论】:

标签: javascript portability


【解决方案1】:

一些想法(我稍后会添加更多):

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

var SMARTQUOTES = SMARTQUOTES || {};

  • 您可以在初始化中添加一个可选的“元素”。比如:
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 文章。 它们是关于模块模式的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-25
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多