【问题标题】:Javascript pattern setup differenceJavascript模式设置差异
【发布时间】:2011-12-21 05:25:50
【问题描述】:

我正在开发一个使用 jQuery 的小型单页滚动网站。作为 javascript 的新手,我遇到过其他开发人员组织代码的许多不同方式。对于一个带有少量 javascript 交互的简单网站,我想知道我在其他网站上看到的以下 sn-ps 代码之间有什么区别。

第一个

var NS = NS || NS
NS = {
    init: function() {},
    buildNav: function() {},
    scrollToSection: function() {}
}

$( document ).ready( NS.init() );

第二

var NS = NS || NS;
NS = new (function() {
    var name = 'Basic';
    var self = this;
    self.getName = function() { return name; };
});
NS.Home = new (function() {
    // variables..are these private or public
    var self = this;
    self.init = function() {
      // initiate
    }

    self.scrollToSection = function() {
      // scroll section
    }

    // public or private method?
    function buildNav() {
    }
});

$(document).ready(function() { NS.Home.init(); });

第三

var NS = NS || NS;

NS.Home = new function() {
  var foo = $('#htmlelement');

  this.scrollToSection() {
    // scroll section
  };
  this.init = function() {
    buildNav();
  };

  function buildNav() { }
}
$( document ).ready( NS.Home.init() );

第四

(function($){
    $.fn.homepage = function() { 
        function buildNav() { }
        function init () { } 
    };
    $.fn.otherpage = function() {
        function doSomething() { }
        function init () { }
     }
})(jQuery);

$(document).ready(function () {
    $('#homepage-element').homepage();
}

【问题讨论】:

  • 你每次都犯一个错误:$( document ).ready( NS.Home.init() ); 这会立即调用该函数 - 删除 () 以将其传递给 ready 函数,以便在 DOM 实际准备好时调用它。跨度>
  • var NS = NS || NS 已过时。
  • ThiefMaster - 所以应该是$( document ).ready( NS.Home.init );
  • var NS = NS || NS 到底在做什么?我已经看到它被用于其他网站。它只是确保 NS 存在吗?我是 JS/jQuery 的新手,所以任何帮助/指向正确的方向都将不胜感激。

标签: javascript namespaces design-patterns


【解决方案1】:

看看 Elijah Manor 提供的 here 的内容。一些关于 javascript 最佳实践的非常好的演示文稿和内容。

【讨论】:

    【解决方案2】:
    1. var NS = NS || NS; 如果传递的值为 null 或未定义,则此行将 NS 初始化为默认值。这三个都创建了一个 NS 的单例对象——它就像一个命名空间。
    2. 第一、第二和第三解释了不同风格的面向对象编程实践。
    3. 首先,NS 对象是通过对象文字表示法创建的,因此它的所有函数都是公共的,您将为 NS 创建的变量也将是公共的。
    4. Second 和 Third 非常相似,除了 Second 更凌乱,Third 更清晰。 Second 和 Third 都在 NS 对象上声明了一些公开的方法(通过匿名构造函数创建)和一些私有函数。
    5. Second 和 Third 使用匿名构造函数动态声明属性。

    您应该阅读一些有关面向对象的 javascript 和设计模式的文章。 以this one开头

    【讨论】:

    • 非常感谢。将在接下来的几天里阅读这些东西!
    猜你喜欢
    • 2023-03-19
    • 2012-12-03
    • 2016-03-20
    • 2013-08-13
    • 2017-11-14
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    相关资源
    最近更新 更多