Object-Oriented Programming with JavaScript, Part II: Methods: Constructing Objects - Doc JavaScript | WebReference

Object-Oriented Programming with JavaScript, Part II: Methods: Constructing Objects - Doc JavaScript


Object-Oriented Programming with JavaScript, Part II: Methods

Constructing Objects

An object constructor is written as a regular function. Here is the Employee object:

function Employee() {
  this.dept = "HR";
  this.manager = "John Johnson";
}

When you create an object, it automatically inherits all Object's properties. The Object object is the base object for all native and user-defined objects. All objects inherit from this superclass. You can create an Object object as well:

var myObject = new Object();

The Object object has a dozen of properties and methods. Examples are constructor, toString(), and valueOf(). The object myObject above sports these properties. Alert the object. You should get [object Object]. You can pass a string to the Object constructor:

var myObject = new Object("foo");

Alert the object. You should get the string you passed to the constructor, "foo". The native objects sports the same properties, because they inherit from the Object class. Probe the constructor property of the Math object, Math.constructor. The answer you should get is that the Object object is the constructor of the Math object.

You can add properties to the object by attaching them to the this value within the constructor function, as shown above. As for the methods, there are three different ways to define them. The simple way calls for normal function creation, inside the constructor function. Let's define a method, setRegisterA():

function Employee() {
  var registerA = "Initial Value";
  function setRegisterA(param) {
    registerA = param;
  }
  this.setRegisterA = setRegisterA;
  this.dept = "HR";
  this.manager = "John Johnson";
}

Let's use it now. First, create a variable of class Employee:

var Ken = new Employee();

And then store a new value in registerA:

Ken.setRegisterA("new value stored in registerA");

Next: How to define a function


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

URL: https://www.webreference.com/js/column80/2.html