What are JavaScript objects and when would they be useful?
I just heard about JavaScript objects and was wondering what they are (because I cannot find any information out there) and what they are useful for.
I really just need开发者_如何学Go help with that. Sorry I am a beginner.
Apart from the few primitive types (numbers, strings, booleans, null and undefined) everything is an object in JavaScript (even functions).
Objects are basically containers of properties, which happen to be very useful for collecting and organizing data.
One popular method to create objects is to use the object literal notation:
var emptyObject = {};
var myFirstObject = {
'name': 'Bobby',
'surname': 'Smith'
};
The quotes around property names are optional if the name would be a legal JavaScript identifier and not a reserved word. A property's name can be any string. Objects can contain other objects, so they can easily represent trees or graphs:
var myFlight = {
'airline': 'Airline Name',
'number': 'AN700',
'departure': {
'IATA': 'SYD',
'time': '2010-09-04 23:10:00'
},
'arrival': {
'IATA': 'LAX',
'time': '2010-09-05 05:14:00'
}
};
JavaScript objects also happen to be a convenient hash table data structure. You could easily do the following:
var myHashTable = {};
myHashTable['name'] = 'Bobby';
myHashTable['surname'] = 'Smith';
alert(myHashTable['name'] + ' ' + myHashTable['surname']);
This is definitely not an exhaustive answer, but I hope it gets you going in the right direction when doing further research.
Well, the best source of information is the ECMASCript specification (of course) :)
In JavaScript there are 6 types.... 5 of them are primitive and the sixth type is object. Objects are all functions, all arrays, host objects (like the window object, the document object, every DOM node), built-in constructor objects (Date, Error, ...), other built-in objects (Math, JSON)...
When someone says JavaScript object, usually he means native objects which are defined in chapter 15. of the ECMAScript spec.
Short answer: it helps if you think in terms of "EVERYTHING is an object".
Longer answer:
Javascript has "data" (for example, your variable "john" and the values it contains) and "functions" (bits of Javascript code that act on data).
An "object" is a programming construct that combines "data" and "functionality" in one place. An "object" is a more powerful construct than either "data" or "functions" regarded separately.
For example, a "shape" object (an "object class") might know how to "draw" itself (an "object method"), regardless of whether it's a "square", a "circle" or a "triangle" (all "object instances").
An "object", as Daniel Vassallo pointed out above, can also be "a container of properties".
'Hope that helps
精彩评论