Tutorial :Which datastructure is this? - Javascript



Question:

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


Solution:1

  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 */ }  }  


Solution:2

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


Solution:3

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »