【发布时间】: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