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";}
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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With