javascripts对象编程技巧

时间:2015-05-28 22:47:57

标签: javascript oop

我是面向对象的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

此代码的目的是习惯于对象的创建和操作。所以我想是否有更简单的方法和更合理的方法来完成同样的任务。

好的任何帮助都将受到赞赏和谢谢。

1 个答案:

答案 0 :(得分:1)

只需查看工厂设计模式以及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
});
希望有所帮助!