hasOwnProperty()  Object  instance method getterS2C Home  « Globals « Object « hasOwnProperty()

Description

Returns a boolean indicating whether the object has the specified direct property.

  • Only direct properties return boolean true.
  • Anything else including methods inherited via the prototype chain such as toString() return boolean false.

Syntax

Signature Description
anObject.hasOwnProperty()Returns a boolean indicating whether the object has the specified direct property.

Parameters

None.

Examples

The code below creates a custom object type function and checks the hasOwnProperty() method in it and properties inherited from the prototype chain.


// Define a custom object type function.
function HomeOwner(firstName,lastName) {  
  this.firstName=firstName;  
  this.lastName=lastName;  
}  
// Check direct properties.
owner = new HomeOwner('Barney','Magrew');  
alert(owner.hasOwnProperty('lastName')); // exists so should be true

// Delete lastName property
delete owner.lastName;  
alert(owner.hasOwnProperty('lastName')); // deleted so should be false

// Check inherited  property
alert(owner.hasOwnProperty('toString')); // inherited so should be false

Press the button below to action the above code:


Related Tutorials

JavaScript Basic Tutorials - Lesson 7 - Objects

go to home page Homepage go to top of page Top