Previous
Next
CSE775 - Distributed Objects

JavaScript Demo3 - JavaScript Objects

JavaScript objects are associative arrays of key, value pairs. The keys are strings and the values can be any JavaScript type even functions and other objects.

JavaScript is a prototype language. We build objects with a constructor function, capitalized by convention, using the syntax:

var myObj = new MyObjectType(arg1, arg2, ...);

Every object has a prototype determined by its constructor function. If you add properties and methods to the prototype they will be available to every object created with the constructor. You can do that by adding them to the constructor code or by adding them directly to the prototype, using the syntax:

myObject.__proto__.myProperty = someLiteral;
myObject.__proto__.myFunction = function() { /* some code here */ };

The language does not have classes or inheritance, but prototypes serve a lot of the same needs. One important point - Javascript does not directly support making properties private. There are alot of ways to approximate this, each with its own weaknesses. It's probably best to just use the language as it was designed.

JavaScript objects are created either by using the new operator on a constructor function or by assigning a variable an object literal. If we define a Constructor function, by convention its first letter is capitalized.

Create object using the Object function constructor:

var myObj = new Object(); myObj.name = "Jim" ...

Create an object from a custom function constructor:

When processing a selection of a property or method, JavaScript looks first at the object, then it's prototype, and then all the way up the prototype chain until it gets to Object.

Create an object from an Object literal:

This works because JavaScript will convert literals to instances of Objects with almost no provication.

Brief look at some Standard Objects:

Date:

var now = new Date(); var hour = Date.getHours();

Math:

var myNum = Math.pow(2,8);
var yourNum = Math.sqrt(3);

Global Object:

We've mentioned the global object. Here it is in all its glory: