Is the Javascript constructor function equivalent / similar to a Java class or interface?

advertisements

I am trying to pick up the basics of Java and I am more familiar with JavaScript.

Is the following statement accurate (I just need high level understanding):

Javascript constructor function or factory function is the equivalent (i am using this word loosely here) of a class or interface in Java.

EDIT:

This is what I am reading in a Java book:

A Java program is mostly a collection objects talking to other objects by invoking each other's methods. Every object is of a certain type, and that type is defined by a class or an interface. Most Java programs use a collection of many different types.

Coming from Javascript, above sounds very much like JS constructor function is similar to a class in Java where the objects properties and methods would be defined.

I know Java and JavaScript are two separate languages.

Thanks


I'd say you're close. Constructor functions (and prototypes) in JavaScript are the closest thing to Java classes that we have in JS; but they're certainly not "equivalent".

You can dynamically add or remove properties and methods to the prototype of a JavaScript constructor; you can't add or remove things from a Java class at runtime.

Example:

function Foo() {}
Foo.prototype.hello = function() { alert('hello'); };

var f = new Foo();
f.hello(); // alerts 'hello'

delete Foo.prototype.hello;

f.hello(); // throws an error

You can achieve "inheritance" at runtime in JavaScript simply by assigning the prototypes of constructor functions to arbitrary objects. In Java you declare inheritance at compile-time and it cannot be changed at runtime.

Example:

function EnglishSpeaker() {}
EnglishSpeaker.prototype.greet = function() { return 'hello'; };

function SpanishSpeaker() {}
SpanishSpeaker.prototype.greet = function() { return 'hola'; };

function Me() {}
Me.prototype = EnglishSpeaker.prototype;

var me = new Me();
me instanceof EnglishSpeaker; // true
me.greet(); // 'hello'

Me.prototype = SpanishSpeaker.prototype;
me = new Me();
me instanceof EnglishSpeaker; // false
me instanceof SpanishSpeaker; // true
me.greet(); // 'hola'

In JavaScript a prototype is simply an object. So a "class" (constructor function) can "inherit" from any plain object; thus there is a much looser distinction between "types" and "values".

Example:

function Thing() {}

var randomObject = { foo: 1, bar: 2 };
Thing.prototype = randomObject;

var thing = new Thing();
thing.foo; // 1

In Java you can define an interface which some class must implement. JavaScript doesn't really provide any such mechanism.

These are just some of the differences off the top of my head. Point is: they're similar, and you're right to draw a connection. But they are definitely not the same.