我对改进我的 javascript 代码以使其成为正确的 OOP 很感兴趣....目前我倾向于做这样的事情:
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 的好资源,或者您对改进我当前的编程风格有什么建议?
看来我应该做一种模型原型(prototype)并让我的 form
对象继承自该原型(prototype)。
(由于与 prototypeJS 冲突,我使用 jQuery 而不是 $)
最佳答案
你的问题很宽泛,所以我认为这里不可能有完整的答案。但这里有几点。
关于您显示的代码。您正在跳几个多余的圈。
- 除非您以某种方式访问 DOM,否则无需将代码包装在
jQuery(document).ready()
中
- 除非您要关闭一些私有(private)函数或数据,否则不需要从自调用匿名函数返回对象
您创建的对象可以像这样更简单地创建(好事)
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
下面是一个使用自调用匿名函数创建私有(private)成员的例子
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 语言那样的类(我会讲到),但在最简单的层面上,创建用于创建特定类型对象的"template"非常容易。这些"template"是称为构造函数的普通函数。
// 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中不是那么直观,因为它是原型(prototype)的。我不会在这里深入,因为你很可能不会直接使用 js 的原生原型(prototype)继承范例。
这是因为有些库可以非常有效地模仿经典继承,Prototype (inheritance)或 mootools (Class)例如。 There是others .
许多人说继承在 OO 中被过度使用,您应该 favour composition这让我想起了我在开始这个漫无边际的回答时最初打算推荐的内容。
JavaScript 中的设计模式与任何 OO 语言中的设计模式一样有用,您应该熟悉它们
我建议您阅读 Pro JavaScript Design Patterns . 就是这样
关于javascript - 在 Javascript 中编程 OOP - 正确地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5823802/