Object-Oriented Programming with JavaScript, Part I: Inheritance: Querying an Object's Properties - Doc JavaScript | WebReference

Object-Oriented Programming with JavaScript, Part I: Inheritance: Querying an Object's Properties - Doc JavaScript


Object-Oriented Programming with JavaScript, Part I: Inheritance

Querying an Object's Properties

JavaScript provides you with a way to loop over an object's properties. You can use this loop technique to find out the names of an object's properties. The looping is done with a for loop:

for (property in objName)

where objName is the name of your object. In the following example we use the for loop to print ken's employee properties (dept and manager):

function employee() {
  this.dept = "HR";
  this.manager = "John Johnson";
}
function printProp() {
  var ken = new employee();
  for (property in ken) {
    alert(property);
  }
}

Try it. You will get two alert boxes: one for dept and one for manager.

Use the hasOwnProperty() method to find out if an object has a certain property you are interested in. The hasOwnProperty() is a method of the Object object, and thus all objects inherit it (all objects are subclasses of the Object object). The following code checks if the object Ken of the Employee subclass has a manager. Try it (IE 5.x and up, Netscape 6 and up), it should give true:

function printProp2() {
  var Ken = new Employee();
  alert(Ken.hasOwnProperty("manager"));
}

An object's property may be enumerable. An enumerable property can assume only predefined values from a given list. The variable a is enumerable:

a = new Array("jan", "feb", "march");

It can assume one of three values only: "jan", "feb", or "march". The following script defines the object Employee1, where the property month is enumerable:

function Employee1() {
  this.dept = "HR";
  this.manager = "John Johnson";
  this.month = new Array("jan", "feb", "mar");
}
var Ken = new Employee1();

You can verify that indeed month is enumerable by:

Ken.month.propertyIsEnumerable(0);

The parameter of the method above should be numeric. Try it (IE 5.x and up, Netscape 6 and up).

Next: How to compare JavaScript and Java

https://www.internet.com


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: March 12, 2001
Revised: March 12, 2001

URL: https://www.webreference.com/js/column79/9.html