首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tips脚本对象编程技巧

tips脚本对象编程技巧
EN

Stack Overflow用户
提问于 2015-05-28 22:47:56
回答 1查看 58关注 0票数 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)

下面是完整的代码示例

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

不管怎么样,我都会感谢你的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-28 23:14:19

只需查看工厂设计模式http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript中的所有其他设计模式即可。这些都是很好的练习,一定会把你推向正确的方向。如果您只是构建一个小型应用程序,那么工厂模式可能会造成一些开销,但是使用单个方法factory.create()创建对象可以让您在将来快速地改变事物。

有些人也喜欢将带有属性的对象传递给工厂。

我会创建一个小工厂来管理这家商店:

代码语言:javascript
复制
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
});

希望这能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30518316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档