- jQuery(document).ready(function () {
- Page.form = (function () {
- return {
- //generate a new PDF
- generatePDF: function () {
- },//Update the list of PDFs available for download
- updatePDFDownloads: function () {
- },/*
- * Field specific functionality
- */
- field: (function () {
- return {
- //show the edit prompt
- edit: function (id,name) {
- },//refresh the value of a field with the latest from the database
- refresh: function (id) {
- }
- };
- }())
- };
- }());
- });
最后它只是主要是有组织的功能,我想…什么是一个很好的资源,我可以学习以OOP方式编写JavaScript,或者你有什么建议可以改善我目前的编程风格?
看起来我应该做一种模型原型并让我的表单对象继承自该原型.
(因为与prototypeJS的冲突,我使用的是jQuery而不是$)
解决方法
>除非您以某种方式访问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) {
- }
- }
- }
- };
它更容易阅读,更容易混淆,只做你买东西的事情.见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 );
- }
- }
- })();
正如你所说,你所使用的结构,对象文字在分组一组函数(方法)和属性时非常好.这是一种命名空间.它也是一种创建Singleton的方法.您可能还想创建同一类的许多对象.
JavaScript没有像传统OO语言那样的类(我会说到这一点),但在最简单的层面上,创建一个“模板”来创建特定类型的对象非常容易.这些“模板”是称为构造函数的常规函数.
- // 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上有很多例子.
继承是OO的基础,在js中并不直观,因为它是原型的.我不会在这里讨论,因为你很可能不会直接使用js的原生原型继承范例.
这是因为有些库可以非常有效地模仿经典继承,例如Prototype (inheritance)或mootools (Class). There是others.
很多人说继承在OO中被过度使用了,你应该favour composition,这让我想到了我在开始这个漫无边际的答案时最初的建议.
JavaScript中的设计模式与任何OO语言一样有用,您应该熟悉它们
我建议你阅读Pro JavaScript Design Patterns.那就是它