Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object definition in 2 ways - what is the difference? [duplicate]

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:

  1. 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?

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

like image 643
Novellizator Avatar asked Aug 06 '13 11:08

Novellizator


3 Answers

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?

like image 77
Brigand Avatar answered Sep 20 '22 03:09

Brigand


The first one creates an instance of an object with two properties. You can access them like this:

User.name; // Tomy
User.password; // secret

The second one creates a definition of an object which you can create separate instances of and they will have separate instances of their properties. Example:

var a = new User();
a.name; // Tomy
a.password; // secret
var b = new User();
b.name = "Ralph";
a.name; // Tomy
b.name; // Ralph
like image 42
Konstantin Dinev Avatar answered Sep 19 '22 03:09

Konstantin Dinev


The two are not remotely equivalent. The first version creates an object, with the properties name and password set. The second version creates a function which has not been execute; there are no properties set until new User is invoked.

like image 34
meagar Avatar answered Sep 17 '22 03:09

meagar