That's right, in javascript, almost everything is an object. But these objects are bit different from what we see in Java, C++ or other conventional languages. An object in JS is simply a hashmap with key-value pairs. A key is always a string, and a value can be anything including strings, integers, booleans, functions, other objects etc. So I can create a new object like this:
var obj = {}; // this is not the only way to create an object in JS
and add new key-value pairs into it:
obj['message'] = 'Hello'; // you can always attach new properties to an object externally
or
obj.message = 'Hello';
Similarly, if I want to add a new function to this object:
obj['showMessage'] = function(){
alert(this['message']);
}
or
obj.showMessage = function() {
alert(this.message);
}
Now, whenever I call this function, it will show a pop-up with message:
obj.showMessage();
Arrays are simply those objects which are capable of containing lists of values:
var arr = [32, 33, 34, 35]; // one way of creating arrays in JS
Although you can always use any object to store values, but arrays allow you to store them without associating a key with each of them. So you can access an item using it's index:
alert(arr[1]); // this would show 33
An array object, just like any other object in JS, has it's properties, such as:
alert(arr.length); // this would show 4
For in-depth detail, I would highly recommend John Resig's Pro Javascript Techniques.
0
Created by craftsman on 2020-03-11 21:26:13 +0000 UTC
Share