February 23, 2001 - Defining Instances | WebReference

February 23, 2001 - Defining Instances

Yehuda Shiran February 23, 2001
Defining Instances
Tips: February 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

As opposed to Java, which is a class-based language, JavaScript is a prototype-based language. This difference is reflected everywhere. The term instance, for example, has a specific meaning in class-based languages. An instance is an individual member of a class. It is an implementation of the class definition. In JavaScript, "instance" does not have this technical meaning, because there is no such difference between classes and instances. However, instance can be used informally to mean an object created using a particular construction function. In the following example:

function superClass() {
  this.bye = superBye;
  this.hello = superHello;
}
function subClass() {
  this.bye = subBye;
}
subClass.prototype = new superClass;
function superHello() {
  return "Hello from superClass";
}
  
function superBye() {
  return "Bye from superClass";
}
function subBye() {
  return "Bye from subClass";
}
var newClass = new subClass();

newClass is an instance of subClass(). It was created according to subClass()'s constructor function.

How would the above example look in a class-based language? In Java, it is translated into something like that:

public class superClass {
  public superClass () {
    this.bye = superBye;
    this.hello = superHello;
  }
}
public class subClass extends superClass {
  public subClass () {
    this.bye = subBye;
  }
}