-1

i'm new to object oriented javascript so while i was practicing i created this code here :

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

the purpose from this code is to get used to objects creation and manipulation . so i waswondering if there is any easier way and more logical method to fulfill the same task .

well anyhelp would be appreciated and thanks.

0

1 Answer 1

1

just have a look at the factory design pattern and all the other design patterns at http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript. They are good practice and will definitely push you in the right direction. The factory pattern could be some overhead if you're just building a small application, but creating objects from a single method factory.create() gives you the ability to change things quickly in the future.
Some people also prefer to pass an object with attributes to the factory.

I would create a tiny factory which manages the store as well:

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
});

hope that helps!

Sign up to request clarification or add additional context in comments.

3 Comments

ty for your help @Jörn i will consider your example .
@Fayçal you're welcome! don't forget to mark this thread as answered if i answered your question :)
well @Jörn ty again i found really good javascript design patterns but i asked this question to get advices and techniques and discuss them with people who know them better than me

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.