Quick Look at JavaScript Objects

  • submit to reddit

I've been working on web based projects built mainly with PHP and JavaScript, where I mostly use Zend Framework and jQuery. I am interested in any webpage optimizations techniques - for a faster web! Stoimen is a DZone MVB and is not an employee of DZone and has posted 50 posts at DZone. View Full User Profile

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);

 

References
0
Tags:

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)