Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Look at JavaScript Objects

DZone's Guide to

Quick Look at JavaScript Objects

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

As you may know there are different notations of objects in JavaScript, and there are slight differences. However here I’m gonna achieve the same thing with different notations. The first one is the object notation in JavaScript known mostly from JSON. There you’ve to construct a key/value pairs, divided by a colon:
var class1 = {
a : 0,
func1 : function() {
console.log(class1.a);
},
func2 : function(a) {
this.a = a;
}
}
class1.func2(3);
Here we have two functions – func1 and func2 and one member variable. Func2 is setting up the member variable, it’s something like a setter in some languages like Java and PHP, and the func1 is printing the value of that variable via console.log(). Note that in the body of func1() the variable “a” is accessed with the class name: class1.a. Here the notation can be changed to this.a, which will result in the same thing.
...
console.log(this.a);
...

Notation #2

While in the notation I’ve just used is not possible to have two different instances from the same class, in the next example this is possible. In JavaScript the objects are even the functions, and you can access the function’s private variables with the dot notation.

var class2 = function() {
this.a = 0;
this.func1 = function() {
console.log(this.a);
}

this.func2 = function(a) {
this.a = a;
}
}

To use this object you’ve to use the “new” operator.

var c = new class2();
c.func2(4);

This helps you create more than one instance of the same class.

var c = new class2();
var d = new class2();
c.func2(3);
d.func2(4);

 

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}