Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

2. Working with Objects and Properties > Encapsulating Complex Objects in a Pro...

Encapsulating Complex Objects in a Programmatically Beneficial Way

The Object(), Array(), and Function() objects can contain other complex objects. Below, I demonstrate this by setting up an object tree using Object() objects.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

// encapsulation using objects, creates object chains
var object1 = {
   object1_1: {
       object1_1_1: {foo: 'bar'},
       object1_1_2: {},
   },
   object1_2: {
       object1_2_1: {},
       object1_2_2: {},
   }
};

console.log(object1.object1_1.object1_1_1.foo); // logs 'bar'

</script></body></html>

The same thing could be done with an Array() object (a.k.a. multidimensional array), or with a Function() object.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

// encapsulation using arrays, creates multidimensional array chain
var myArray= [[[]]]; /* an empty array, inside an empty array, 
                     inside an empty array */

/* Here is an example of encapsulation using functions: an empty function 
inside an empty function inside an empty function. */
var myFunction = function() {
   // empty
   var myFunction = function() {
       // empty
       var myFunction = function() {
          // empty
       };
   };
};

// we can get crazy and mix and match too
var foo = [{foo: [{bar: {say: function() {return 'hi';}}}]}];
console.log(foo[0].foo[0].bar.say()); // logs 'hi'

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint