Simple Object vs. Factory vs. Constructor

There are three ways of creating objects in JavaScript:

  • by simple Object creating
  • by Factory function
  • by Constructor function

  • Simple Object Creation:

    var ronaldo = {
        name: "Ronaldo",
        age: "35",
        quote: "Hi I am Ronaldo", 
        salary: function(x){ return x+2500; }
    };
    
  • Factory Function:

    function human(x,y,z,i){
        return{
            name: x,
            age: y,
            quote: z,
            salary: function(i){ return i+2500; }
        }
    };
    var Zini = human('Zenidan','41','I am Zidane',7500);
    
  • Constructor Function:

    var human = function(x,y,z,i){
        this.name = x,
        this.age = y,
        this.quote = z, 
        this.salary = function(i){ return i+2500; }
    };
    var Lampd = new human('Frank Lampard','39','I am Frank J Lampard',5500);
    
  • Can someone provide simple illustrations of when to use which of these methods to create objects in simple terms, so that a naive can also understand?

    I went through the following links, but it's a bit complicated to understand:

  • Constructors vs Factory Methods
  • Constructor function vs Factory functions
  • Creation of Objects: Constructors or Static Factory Methods
  • So I'm asking for some simple practical cases.


    Use simple objects for data: when all you need is a bundle of key/value pairs.

    In your example of a simple object, you have more than just data: the salary method adds behavior to the object. If you're going to end up with many objects like that, it's better for performance and maintainability to have just one salary method that is shared between all of the objects, rather than each object having its own salary method. A way to share a method among many objects is to put the method on a prototype of the objects.

    You can use a constructor function when you need to create an object that is an instance of a prototype. This is a good place to read about that, but it's a little dense: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

    The MDN link above also demonstrates ECMAScript 2015 class syntax, which is an alternative to constructor functions.

    Update: See Dave Newton's comment for a good example of when to use a factory

    链接地址: http://www.djcxy.com/p/30166.html

    上一篇: 为什么Jenkins在通过密钥后仍然要求输入ssh密码?

    下一篇: 简单对象与工厂与构造函数的比较