HTML and CSS Reference
In-Depth Information
This test passes because we now filter out properties added to the proto-
type chain. There are two things to keep in mind when dealing with Object.
prototype.hasOwnProperty .
Some browsers, such as early versions of Safari don't support it.
Objects are frequently used as hashes; there is a risk of hasOwnProperty
being shadowed by another property.
To guard our code against the latter case, we can implement a custom method
that accepts an object and a property and returns true if the property is one of
the object's own properties, even when the object's hasOwnProperty method is
shadowed or otherwise unavailable. Listing 7.10 shows the method. Add it to the
tdd.js file from Chapter 6, Applied Functions and Closures.
Listing 7.10 Sandboxed hasOwnProperty
tddjs.isOwnProperty = (function () {
var hasOwn = Object.prototype.hasOwnProperty;
if (typeof hasOwn == "function") {
return function (object, property) {
return, property);
} else {
// Provide an emulation if you can live with possibly
// inaccurate results
For browsers that do not support this method we can emulate it, but it is not
possible to provide a fully conforming implementation. Chances are that browsers
that lack this method will present other issues as well, so failing to provide an
emulation may not be your main problem. We will learn techniques to deal with
such cases in Chapter 10, Feature Detection.
Because properties are always enumerable when added by JavaScript, and
because globals make it hard for scripts to co-exist, it is widely accepted that
Object.prototype should be left alone. Array.prototype should also be
treated with care, especially if you are using for-in on arrays. Although such loops
should generally be avoided for arrays, they can be useful when dealing with large,
sparse arrays.
Search WWH ::

Custom Search