Object-Oriented Programming with JavaScript, Part I: Inheritance: Comparing between JavaScript and Java - Doc JavaScript | WebReference

Object-Oriented Programming with JavaScript, Part I: Inheritance: Comparing between JavaScript and Java - Doc JavaScript


Object-Oriented Programming with JavaScript, Part I: Inheritance

Comparing JavaScript and Java

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, the term "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;
  }
}

Next: A Final Word

http://www.internet.com


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

URL: http://www.webreference.com/js/column79/10.html