tags:

views:

126

answers:

3

I came across a code snippet in JS

globe =
{
   country : 'USA',
   continent : 'America'
}

Using the variable declared above by:

alert(globe.country);

Questions:

  1. Is this a JS class with 2 members?
  2. Why is the var keyword not used when declaring globe?
  3. If it's a class, can I have member functions as well?

Thanks

+3  A: 

That is a JavaScript object. Written in the object literal notation.

Lark
+11  A: 
  1. That is a JS object with two properties.

  2. Not using var places the variable in the global scope

  3. Though not a class, it can still have functions as properties

The functions can be tacked on two different ways:

globe.myFunc = function() { /* do something */ };

or

globe = {
    ...
    myFunc: function() { /* do something */ }
}
geowa4
My background is in C#. In C#, an object is an instance of a class. It appears that in JS, the class is called as an object?
js has no "class". it only has objects. functions are first-class objects and new "instances" can be created using the `new` keyword.
geowa4
there are no classes in ECMAScript; you can mimic the functionality of a class by defining a constructor function and using the new keyword to create objects. I suggest familiarizing yourself with prototypal inheritance.
meder
JS doesn't have formal classes, it just has objects and uses a prototype based inheritance system. You should do more research in to how JS represents objects, how its prototype inheritance works, and how some mimic more conventional class based OO techniques built on top of JS's system.
Will Hartung
Thanks, I will definitely look into the inheritance system. If I were to compare any OOP language to JavaScript, which of these have native support in JS (or can be mimicked in some way) - Abstraction, Polymorphism, Inheritence, Encapsulation?
encapsulation requires some tricky programming. polymorphism isn't necessary since there are no types; you could do some things to make sure that you are dealing with the right type of object though. but everything that you ask in that comment should be in their own questions on SO.
geowa4
+1  A: 

JavaScript is not an object-oriented language so there are not classes in the same sense as in a language like Java or C#. JavaScript is a prototype based language. So this is an object with two members. You can add additional members like you would to any other object and they can be functions.

Amuck