The ECMAScript-262 revision 3 specification includes a method named hasOwnProperty
which must be present on all objects. From the spec:
Object.prototype.hasOwnProperty (V)
When the hasOwnProperty method is called with argument V, the following steps are taken:
- (ECMA-262, 3rd edition, page 85, section 15.2.4.5)
- Let O be this object.
- Call ToString(V).
- If O doesn't have a property with the name given by Result(2), return false.
- Return true.
Safari (up to and including version 2.0) does not support this method.
var theObj = { foo : 'yum' };
if ( theObj.hasOwnProperty )
{
document.write( "Has 'foo': " + theObj.hasOwnProperty( 'foo' ) + '\n' );
document.write( "Has 'bar': " + theObj.hasOwnProperty( 'bar' ) + '\n' );
}
else
{
document.write( "ERROR: ECMAScript hasOwnOwnProperty() method missing!" );
}
Has 'foo': true
Has 'bar': false
//Simplistic version for illustration purposes only
Object.prototype.toSourceCode = function( )
{
var theSourceCode = '{\n';
for ( var thePropName in this )
{
if ( !this.hasOwnProperty || this.hasOwnProperty( thePropName ) )
{
theSourceCode += ' ' + thePropName + ' : ' + this[ thePropName ] + ',\n';
}
}
return theSourceCode.replace( /,\n$/, '\n}' );
}
var theHash = { size:12, count:53, tax:0.06, sku:8295193 };
document.write( theHash.toSourceCode( ) );
{
size : 12,
count : 53,
tax : 0.06,
sku : 8295193
}
{
toSourceCode : function ()
{
var theSourceCode = "{
";
for (var thePropName in this)
{
if (!this.hasOwnProperty || this.hasOwnProperty(thePropName))
{
theSourceCode += " "+thePropName+" : "+this[thePropName]+",
";
}
}
return theSourceCode.replace(,\n$, "
}");
},
size : 12,
count : 53,
tax : 0.06,
sku : 8295193
}
{
size : 12,
count : 53,
tax : 0.06,
sku : 8295193
}
{
size : 12,
count : 53,
tax : 0.06,
sku : 8295193,
toSourceCode : function( )
{
var theSourceCode = '{\n';
for ( var thePropName in this )
{
if ( !this.hasOwnProperty || this.hasOwnProperty( thePropName ) )
{
theSourceCode += ' ' + thePropName + ' : ' + this[ thePropName ] + ',\n';
}
}
return theSourceCode.replace( /,\n$/, '\n}' );
}
}
{
size : 12,
count : 53,
tax : 0.06,
sku : 8295193
}