0

Need to know which is the correct way of implementing the constructor function from these two options.

var Dog=function(name,bread)
{
    return {

        name:name,
        bread:bread

    }

}

function Dog(name,bread)
{
    var new_object= this;

    new_object.name=name;
    new_object.bread=bread;
}
sameer
  • 1,635
  • 3
  • 23
  • 35
  • 2
    The answer, is of course, it depends. Both are fine, although the first would be named a 'factory function' rather than a constructor. – Jared Smith Jun 16 '16 at 14:13
  • 3
    The first is what we call a *factory*, not a constructor. The second uses a completely unnecessary, an [implicitly global](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) variable instead of `this` – Bergi Jun 16 '16 at 14:14
  • The are no constructor function implementations in your snippets. – Redu Jun 16 '16 at 14:18
  • @Bergi, Corrected the typo missed adding var. – sameer Jun 16 '16 at 14:20
  • @all , reason for this question is that,have came across this two ways of construct function which does the same thing, need to know significance of each. Intent was somebody who knows javascript well can guide me. Excuss me if this question sound stupid. – sameer Jun 16 '16 at 14:27

2 Answers2

1

The is not one correct way to do that in JavaScript. Refer to this answer to see the different patterns that you can use to program in an object-oriented way in JavaScript: https://stackoverflow.com/a/30148923/1566187

Community
  • 1
  • 1
Ely
  • 10,860
  • 4
  • 43
  • 64
0

It depends on what you want to do with it, but if you're looking for a simple constructor I'd recommend

function dog(name,breed) {
    this.name = name;
    this.breed = breed;
}

This way you can create new objects easily using that constructor:

var Dog = new dog("Jacky", "Corgi");
var Puppy = new dog("T-Rex", "Yorkshire");

Hope this helps. :)

AryKay
  • 308
  • 1
  • 8