Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

function student(name, age, avgGrade) {
  this.name = name
  this.age = age
  this.grade = avgGrade
}

var student1 = new student("Sharon", 16, 85)
student1.sex = "female"
var message = student1.name + " is a cute " + student1.age
message += " - year old "
message += (student1.sex == "female") ? "girl." : "boy."
alert(message)


Figure 12-2.  A simple message constructed off an object's properties, including the ones assigned to it after it was constructed.

Its output is:


Figure 12-3.  A message generated according to an instance's properties.

The problem with the preceding script is that it adds the new property only to one instance, student1. Because constructor functions are just like any other function, you can use valid JavaScript statements in them. Therefore, you can use the following constructor function to add the new property to all instances of the student object:

function student(name, age, avgGrade, sex) {
  this.name = name
  this.age = age
  this.grade = avgGrade
  this.description = (sex == "female") ? "girl" : "boy"
}

Now you can create instances that will include the “girl” or “boy” description:

var student2 = new student("Joe", 16, 91, "male")

Like before, you can use these properties for many purposes, such as displaying messages:

The keyword this refers to the calling object. When you use it in a constructor function it refers to the instance that calls the function. For example, if student2 calls the constructor function student(), the keyword this inside the function refers to student2. Therefore, the statement

this.name = name

creates a new property of the instance student2 and initializes it with the corresponding value.

Based on the exact definition of the word this, some JavaScript tends to use alternative structures for construction functions. Here is the preceding example in a different form:

function student(name, age, avgGrade, sex) {
  obj = this
  obj.name = name
  obj.age = age
  obj.grade = avgGrade
  obj.description = (sex == "female") ? "girl" : "boy"
}


Figure 12-4.  The undercover value of this inside a constructor function.

Notice that the calling object, referred to as this, is assigned to a variable. This variable must be global because a constructor function’s purpose is to create an instance for use outside of that function. A local variable does not have any effect outside the function where it is declared. It is recommended that you do not use this form of constructor functions; it is better to get used to the keyword this.

Another key concept to remember is that a constructor function cannot include any direct reference to an existing instance of that object. According to this rule, the following script generates an error:

function student(name, age, avgGrade, sex) {
  this.name = name
  this.age = age
  this.grade = avgGrade
  this.description = (sex == "female") ? "girl" : "boy"
  alert("student3 = " + student3.name)
}

var student3 = new student("Kelly", 15, 78, "female")

You can only refer to the elements of an instance after it has been created, because the constructor function actually works by returning the calling data structure. You can, however, refer to a specific instance inside a constructor function if it was created by a different constructor function or by a previous call to the current constructor:

function student(name, age, avgGrade, sex) {
  this.name = name
  this.age = age
  this.grade = avgGrade
  this.description = (sex == "female") ? "girl" : "boy"
  if (name == "Joe")
  alert("student3 = " + student3.name)
}

var student3 = new student("Kelly", 15, 78, "female")
var student2 = new student("Joe", 17, 91, "male")

In this script segment the constructor function checks if the name of the calling object is “Joe.” If so, it displays the name of student3, which was created earlier by the same function.

Keep in mind that the keyword this refers to the calling object. The undercover value of the word this is an object. The statement

alert(this)

prints the string value of the keyword this in a constructor function.

You now know how to define properties via constructor functions. If you only want to create one instance of an object, you must also use a constructor function.

To view the properties of an object you can use the function presented in Chapter 8, Control Structures:

function getProps(obj, objName) {
  var result = "" // initialize output string

  for (var i in obj) {
 result += objName + "." + i + " = " + obj[i] + "<BR>"
  }
  result += "<HR>" // add horizontal rule to output string
  return(result) // return output string
}

To invoke this method use a statement such as:

document.write(getProps(student1, "student1"))

Note that the arguments are not always the same. For example, if you use this statement from within another function that accepts the instance student1 as the parameter person, you should use the following statement instead:

document.write(getProps(person, "student1"))

If a property of an object holds a null value, it does not exist. Assigning a null value to a property will cause the function getProps() to count out that property. Keep this in mind, especially when you are debugging a script.

Nested Objects

JavaScript supports nested objects. A nested object is an object that is also a property of another object. There are a few ways to create nested objects. We will present the most convenient one.

Take a look at the following script portion:

function student(name, age, grade, father, mother) {
  this.name = name
  this.age = age
  this.grade = grade
  this.parents = new parents(father, mother)
}

function parents(father, mother) {
  this.father = father
  this.mother = mother
}

var student1 = new student("Sharon", 16, 85, "Mark", "Stacy")

This script consists of two functions. The function parents() creates an instance containing two properties, father and mother. It accepts both values as arguments.

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us