HTML and CSS Reference
In-Depth Information
helps reduce the possibility of naming collisions. The following code demonstrates this strat-
egy to create a namespace for a library developed for a bookstore:
var com = {};
com.Bookstore = {};
com.Bookstore.Book = {
title: 'my book',
genre: 'fiction'
};
com.Bookstore.Author = {
firstName: 'R',
lastName: 'D'
}
By creating the objects in this way, you can be reasonably certain that if another developer
creates a useful library to manage topics that you want to include in your site, you won't have
to worry about a naming collision between your
Book
and
Author
objects and those provided
by the other library. When developing reusable JavaScript libraries, never implement your
objects in the global namespace.
The keyword
this
is a special term that allows JavaScript developers to reference the contain-
ing object directly. The following code snippet demonstrates the context of the
this
keyword:
<script>
//Here, "this" references the global namespace
this.navigator.geolocation
window.onload = function () {
//Here, "this" references the window object
this...
document.getElementById("aDiv").onclick = function()
{
//Here, "this" references the DIV element
this…
}
}
</script>
In this code snippet, the first
this
reference is in the global namespace—so it provides a
direct reference to the global namespace. As you move down through the code, the context
of the
this
keyword changes. In the onload event for the window,
this
refers to the
window
object (yes, that's in the global namespace, but keep reading). Within the
onclick
function,
the
this
keyword refers to the
div
element returned from the
getElementById
method. The
this
keyword always refers to the object that contains the currently running code. That is its
context.
Search WWH ::
Custom Search