JavaScript Objects and Properties (The Good Stuff)   Leave a comment

dlr2008

Everything in JavaScript is an object. The names are changed to confuse the innocent. JavaScript Object can have “properties” but these are themselves, objects. So a JavaScript object is composed of a list (dictionary) of objects (properties). Some objects hold simple (primitive) values (numbers, strings), some objects hold (are) functions. So let’s begin.

The Basics

  • var a=new Object();
    
    • Create a new, 'empty' object.
      
  • a["Alpha"]="Simple String";
    
    • Add a property, a 'string' object
      
  • a.Alpha="Simple String";
    
    • Add a property, alternative, common syntax
      
  • a="{Alpha : 'Simple String'};
    
    • YAS (Yet another syntax – Introducing Object Literal Syntax)
      
  • a.Alpha
    
    • returns 'Simple String'
      
  • a["Alpha"]
    
    • Alternative Syntax, same results
      

Identifier Issues

You might ask yourself if "Alpha" is an object owned by the object "a"; who owns "a"?  Every object exists in the CONTEXT in which it is created.  Therefore "a" is a property of its containing context.  Since this is raw code we can use the "this" object to identify that context.  So we can write:
  • this["a"]["Alpha"]
    
  • this.a.Alpha
    
    • Compact, alternative syntax.
      
There are a couple of issues here.  It is possible to create a property name in one syntax which is illegal in the alternative syntax.  This is legal
  • a["0"]=0;
    
    • but watch out, the next line is an error:
      
  • var b=a.0;
    
    • Syntax error.  Identifiers cannot begin with a number.
      
  • var b=a["0"];
    
    • This is legal.
      

Who’s Is On First

How do we know what objects are associated with an object. How do we know what properties are associated with the dictionary of the master object? To do this we will use a JavaScript intrinsic: typeof. The intrinsic typeof takes an identifier as an argument and returns a string.

  • var a=new Object();
  • a["Alpha"]="Simple String";
  • typeof(a) returns "object"
  • typeof(a.Alpha) returns "string"
  • typeof(this.a) returns "object"
  • typeof(this.a.Alpha) returns "string"
  • typeof(a.Beta) returns "undefined"
  • typeof(b) returns "undefined"
  • typeof(b.x) returns a SYNTAX ERROR
    • We can avoid this syntax error only by first testing whether the parent exists (typeof(b)!='undefined')
    • We can package this nested testing into a pair of JavaScript functions:
      • function IfObject(context,objectName){

        if (typeof(context)==='undefined'){

                          return false;

                      }

                      if (typeof(context[objectName])==='undefined'){

                          return false;

                      }

                      return true;

    • }
      • function IfPropertyExists(context,objectName,propertyName){

              if (!IfObject(context,objectName)){

                  return false;

              }

              if (context[objectName][propertyName]=='undefined'){

                  return false;

              }

              return true;

      }

              }

    • IFPropertyExists(this,"b","x") returns false
      • And no syntax error!

    We can iterate through the objects within a parent object as follows:

    • var a=new Object();
    • a["Alpha"]="Simple String";
      
    • a["Beta"]='Second String';
      
    • for (var propName in a) {
      
    •      alert("a["+propName+"] equals " +  a[propName]);
      
    • }
      
      • Returns
        
        • a["Alpha"] equals Simple String
          
        • a["Beta"] equals Second String
          

Object Literal Notation

Object Literal Notation, whose reigning expert is Douglas Crockford, is also known as JSON (JavaScript Object Notation), is increasingly important in all types of JavaScript programming not least of which is has the preferred method of delivering data payloads using AJAX. We can repeat the discussion above using Object Literal Notation.

  • var c={Alpha : 'Simple String', Beta : 'Second String'};
    • c["Alpha"] returns "Simple String"
    • c.Beta returns "Second String "

Now let’s turn it up a notch and add a function as a property object using JSON:

  • var d={Alpha : 'Simple String', Beta : function(){ return 'Dennis';}};
  • d.Beta() returns 'Dennis'
  • d["Beta"]() returns 'Dennis'

If the JSON is stored in a string (think AJAX data package) we can unpack the object using the eval intrinsic.

  • var objectLiteralString="{Alpha : 'Simple String', Beta : function(){ return 'Dennis';}}";
    
    • objectLiteralString now equals the STRING "{Alpha : 'Simple String', Beta : function(){ return 'Dennis';}}"
      
    • Wrap the string in parenthesis and call the eval intrinsic to re-hydrate the object

  • var e=eval("("+objectLiteralString+")");
  • e.Beta() returns "Dennis"
    
  • e["Alpha"] returns "Simple String"

Get it? Good.

EndNote:

We seem to have wandered into the topic of functions here, so let me add an end note on passing objects as parameters. When using an object as a parameter argument the object is passed “by reference”. That means that the object pointer cannot be changed but, stay awake here, the properties of the object may be modified and the modification will be ‘seen’ outside of the function. Let see this by example:

  • var Gamma={a: "first", b:"second", shout : function(){return 'WOW';}};
    
    • Gamma.shout() returns "WOW"
      
  • function DogVoice(){return 'Bark';}
    
    • This defines a new function object which we want to replace for the shout function property of the object Gamma
  • function PassByReference(_objectRef,_propertyName,_newFunction){
    
    _objectRef[_propertyName]=_newFunction;
  • }
  • Now use the function
  • PassByReference(Gamma,"shout",DogVoice);
    
  • Gamma.shout() returns "Bark"
    
    • The shout function has been changed from inside of the external function

    • We cannot assign a new value to Gamma inside of a function
  • function DoesNotWork(_objectRef){
    
    _objectRef=null;
    
  • }
    
    • Define the function and then use it
      
  • DoesNotWork(Gamma);
    
    • Call the function, assign null to Gamma within the function;

    • But this will have no effect on the Gamma outside of the function
  • typeof(Gamma) returns "object"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s