我对面向对象的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)此代码的目的是适应对象的创建和操作。所以我想知道是否有更简单的方法和更合理的方法来完成同样的任务。
不管怎么样,我都会感谢你的。
发布于 2015-05-28 23:14:19
只需查看工厂设计模式和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
});希望这能帮上忙!
https://stackoverflow.com/questions/30518316
复制相似问题