Object definition in 2 ways - what is the difference?

class, javascript, oop

Solution

In this example, `User` now holds an object.

var User = {name:"Tomy", password:"secret"}
typeof User === "object"
User.name === "Tomy"

In this example, `User` will hold a function. This function can be used to create objects.

var User = function () {this.name="Tomy"; this.password="secret";}
typeof User === "function"
User.name === undefined

You could then create as many users as you like.

var user1 = new User(), user2 = new User();
user1.name === "Tomy"

A more realistic example, would be this:

var User = function (name, pass) {this.name=name; this.password=pass;}

var john = new User("John", "secret")
var andrew = new User("Andrew", "passw0rd")

john.password === "secret"

Generally constructors (functions that make objects) are more flexible than object literals, and allow for convenient and consistent creation of objects (bugs are easier to spot, less duplicate code).

There are no cross-browser inconsistencies in the two methods.

To understand what the `new` keyword is and what effectively happens at the "moment of creation", see What is the 'new' keyword in JavaScript? and How does the new operator work in JavaScript?

Problem

I'm new to objects in javascript. Read up on this topic on https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript and got a little confused. I don't understand the difference between functions and objects. On the one hand, function is supposed to be and instance of Function (which is a child of Object) and so a function is also supposed to be an Object. On the other hand object itself is denoted as a key-value pair, such as: `var User = {name:"Tomy", password:"secret"}` and this is quite different from a function definition in terms of code compatibility... Can I create function isn two different ways? `var User = function () {this.name="Tomy"; this.password="secret";}`

Original source

Related problems