创建javascript类时使用什么模式? [英] what pattern to use when creating javascript class?
问题描述
用Java创建类的最佳方法是什么(如在OOP中)? 现在,我正在使用以下模式.可以吗?
what is the best way to create classes ( as in OOP) in Javascript ? Right now I am using the following pattern . Is it ok ?
var myclass = (function() {
var _name;
var baseObject = {
a: 10,
c: function() {
return _name + " world " + privateFunc();
}
};
function privateFunc() { return _name + "-ba"; };
function myclass(name) {
_name = name;
this.x = 9;
};
myclass.prototype = baseObject;
return myclass; })();
推荐答案
没有最佳"方法. JavaScript中有一些OOP模式,您提到的是其中一种(也是流行的一种).本质上,它是一种原型(或伪古典)模式,带有用于封装基于私有类的静态变量的闭包.
There is no "best" way. There are a few OOP patterns in JavaScript, and the one you mentioned is one of them (and also a popular one). It is essentially a prototypical (or pseudo-classical) pattern with a closure to encapsulate private class-based static variables.
还有其他模式(例如,道格拉斯·克罗克福德(Douglas Crockford)推荐的功能模式).
There are other patterns (e.g. the functional pattern recommended by Douglas Crockford).
我个人建议使用伪古典模式(尽管哪种模式最好是争论的热点).
I personally recommend the pseudo-classical pattern (although which pattern is best is a hot area of debate).
如果您要使用JavaScript进行OOP,我强烈,建议您考虑采用内置OOP的JavaScript库,例如关闭库.其他库(例如jQuery,MOOtools,Ext等)都具有OOP模块和/或插件.
If you are doing OOP with JavaScript, I strongly recommend that you look into adopting a JavaScript library that has OOP built in, such as The Dojo Toolkit or the Closure Library. Other libraries (e.g. jQuery, MOOtools, Ext etc.) all have OOP modules and/or plugins.
这篇关于创建javascript类时使用什么模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!