Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  66] [ 2]  / answers: 1 / hits: 36929  / 13 Years ago, thu, february 2, 2012, 12:00:00

I read this a lot in many JavaScript introductions. I just don't understand it. I always think of objects as something with methods and properties.
Arrays I understand, since it has key value pair.
How about Strings or Numbers or functions ?
These things above listed seem to be like functions to me. This means you input something, you get something out. You don't really get the access properties or anything. There's no dot notation used in arrays or this list of objects.



Does anyone code some examples of each of these with dot notations which its methods and properties are being accessed? I suspect that definition of object is probably limited since I did start learning about JavaScript...


More From » oop

 Answers
22

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 or a symbol, 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 a 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 its index:


alert(arr[1]); // This would show 33

An array object, just like any other object in JS, has its properties, such as:


alert(arr.length); // This would show 4

For in-depth detail, I would highly recommend John Resig’s Pro JavaScript Techniques.


[#87681] Tuesday, January 31, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranavrorys

Total Points: 466
Total Questions: 87
Total Answers: 115

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
pranavrorys questions
Fri, May 27, 22, 00:00, 2 Years ago
Thu, Oct 28, 21, 00:00, 3 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Fri, Dec 20, 19, 00:00, 5 Years ago
;