4

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 Answers 3

11
  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 */ }
}
Sign up to request clarification or add additional context in comments.

6 Comments

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.
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.
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.
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?
|
3

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.