您的问题非常广泛,因此我认为这里不可能给出完整的答案。但这里有几点。
关于您所显示的代码。你正在跳几个多余的圈。
- 除非您以某种方式访问 DOM,否则无需将代码包装在
jQuery(document).ready()
- 除非您关闭某些私有函数或数据,否则不需要从自调用匿名函数返回对象
您创建的对象可以像这样更简单地创建(一件好事)
var Page = {
form: {
//generate a new PDF
generatePDF: function () {
},
//Update the list of PDFs available for download
updatePDFDownloads: function () {
},
/*
* Field specific functionality
*/
field: {
//show the edit prompt
edit: function (id, name) {
},
//refresh the value of a field with the latest from the database
refresh: function (id) {
}
}
}
};
它更容易阅读,也更容易混淆,只做那些能给你带来东西的事情。看货物崇拜编程 http://en.wikipedia.org/wiki/Cargo_cult_programming
这是一个使用自调用匿名函数来创建私有成员的示例
var Obj = (function() {
privateFunction( param ) {
// do something with param
}
var privateVar = 10;
return {
// publicMethod has access to privateFunction and privateVar
publicMethod: function() {
return privateFunction( privateVar );
}
}
})();
正如您所说,您使用的结构,对象文字非常适合对一组函数(方法)和属性进行分组。这是一种命名空间。这也是一种创建方式辛格尔顿 http://en.wikipedia.org/wiki/Singleton_pattern。您可能还想创建同一类的许多对象。
JavaScript 没有像传统的面向对象语言那样的类(我会谈到这一点),但在最简单的层面上,创建一个“模板”来创建特定类型的对象是非常容易的。这些“模板”是称为构造函数的普通函数。
// a constructor
// it creates a drink with a particular thirst quenchingness
function Drink( quenchingness ) {
this.quenchingness = quenchingness;
}
// all drinks created with the Drink constructor get the chill method
// which works on their own particular quenchingness
Drink.prototype.chill = function() {
this.quenchingness *= 2; //twice as thirst quenching
}
var orange = new Drink( 10 );
var beer = new Drink( 125 );
var i_will_have = ( orange.quenchingness > beer.quenchingness )
? orange
: beer; //beer
var beer2 = new Drink( 125 );
beer2.chill();
var i_will_have = ( beer2.quenchingness > beer.quenchingness )
? beer2
: beer; //beer2 - it's been chilled!
关于构造函数有很多东西需要了解。你必须四处寻找。 SO 上有很多例子。
继承是面向对象的基础,但在 js 中并不那么直观,因为它是原型的。我不会在这里讨论这个,因为你很可能不会直接使用 js 的原生原型继承范例。
这是因为有些库可以非常有效地模仿经典继承,原型(继承) http://prototypejs.org/learn/class-inheritance or mootools(类) http://mootools.net/docs/core/Class/Class例如。There http://ejohn.org/blog/simple-javascript-inheritance/ are others http://dean.edwards.name/weblog/2006/03/base/.
许多人说继承在面向对象中被过度使用,你应该青睐成分 http://en.wikipedia.org/wiki/Design_Patterns这让我想到了当我开始这个漫无目的的答案时我最初打算推荐的内容。
JavaScript 中的设计模式与任何 OO 语言中的设计模式一样有用,您应该熟悉它们
我建议你阅读专业 JavaScript 设计模式 https://rads.stackoverflow.com/amzn/click/com/159059908X。
在那里,就是这样