2015-05-28 64 views
0

我是新的面向对象的JavaScript因此,虽然我在练习我创造了这个代码在这里:的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) 

Here's the full code sample

从这段代码的目的是为了获得用于创建和操作对象。所以我想知道是否有更简单的方法和更合理的方法来完成相同的任务。

好anyhelp将不胜感激,并表示感谢。

+0

@ray这是一个可怕的建议。 – zerkms

+0

ty @ray我真的很感谢你的忠告再次。 –

回答

0

只是看看工厂设计模式和所有其他设计模式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 
}); 

希望帮助!

+0

ty你的帮助@Jörn我会考虑你的榜样。 –

+0

@Fayçal不客气!如果我回答了你的问题,请不要忘记将此线程标记为已回答:) –

+0

well @Jörnty我再次发现了非常好的javascript设计模式,但我问了这个问题以获得建议和技巧,并与认识他们的人讨论得比我 –