HTML and CSS Reference
In-Depth Information
Implementing native objects
Native objects are available to developers directly through JavaScript. JavaScript provides a
large number of objects that provide functionality to make developers' lives easier. Although
covering every native object in JavaScript is out of scope for this topic and this exam, you will
be expected to be able to create and work with native JavaScript objects.
Some native objects are available statically, which means you don't need to create an
instance of them. Others require you to create an instance. You can find both types among
objects in the global namespace. One example of a static object is Math , which is available in
the global namespace and provides a great deal of functionality without you having to create
an instance:
var squareValue = Math.sqrt(144);
Other objects, such as Array shown in the following code, require you to create an instance
to work with them:
var listofPrimeNumbers = new Array(1, 2, 3, 5, 7, 11, 13, 17, 19, 23);
This code introduces the new keyword, which you use to instantiate an object. This tells the
runtime to allocate a new object of the type specified. In this case, a new Array object is being
requested. The list after the Array object type is called the object's constructor. This informa-
tion can be passed into the object as parameters to construct the initial state of the object.
Some objects have many constructors to choose from, with differing sets of parameters. The
addition of multiple constructors is called an overloaded constructor .
JavaScript also provides wrapper objects. These wrap up native types, for example. Native
types are defined as integer, string, char, and so on. When a variable is declared like this,
var txt = "my long string";
var num = 5;
you can access method on the variable like this:
var index = txt.indexOf("long",0);
var exp = num.toExponential(5);
The underlying types for string and integer don't natively have methods or functionality;
however, the JavaScript runtime creates a wrapper object for them dynamically so that some
useful methods are available. For example, you could create the following string and number
variables with the new keyword, but that's not very common.
var txt = new String("my long string");
var num = new Number(5);
The syntax reviewed thus far applies to both native objects and custom objects. Custom
objects are created by the developer, whereas native objects are provided by core JavaScript.
Search WWH ::

Custom Search