我是面向对象javascript的新手,所以当我在练习时,我在这里创建了以下代码:
ap = []; //creating an empty array to hold persons;
pp = function (f, l, a, n, g) { //this is our object constructor
this.fname = f;
this.lname = l;
this.dob = a;
this.nat = n;
this.gen = g;
};
ap[ap.length] = new pp(f, l, a, n, g); // adding the newely created person to our array through the constructor function . btw parameters passed to the function are defined in another function ( details in the jsfiddle file)
下面是完整的代码示例
这段代码的目的是为了习惯对象的创建和操作。所以我想知道是否有更简单和更合乎逻辑的方法来完成同样的任务。
好吧,任何帮助都将是感激和感谢。
看看工厂设计模式和http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript上的所有其他设计模式。它们是很好的实践,肯定会把你推向正确的方向。如果您只是构建一个小型应用程序,那么工厂模式可能会带来一些开销,但是从单个方法factory.create()
创建对象使您能够在将来快速更改内容。有些人还喜欢将带有属性的对象传递给工厂。
我将创建一个小工厂,同时管理商店:
var ppFactory = {
_store: [],
_objectClass: PP,
create: function (args) {
var pp = new this._objectClass(args);
this._store.push(pp);
return pp;
},
remove: function (id) {
},
get: function (id) {
}
};
var pp = ppFactory.create({
f: f,
l: l,
a: a,
n: n,
g: g
});
希望有帮助!