views:

89

answers:

3

I have a JavaScript class, and I would like to make it so it can't be subclassed. (Similar to marking a class with the "final" keyword in Java.) Here's my JavaScript class:

function Car(make, model) {
     this.getMake = function( ) { return make; }
     this.getModel = function( ) { return model; }
}
+1  A: 

Given that JavaScript doesn't even actually have classes (it's a prototype-based object system, not a class-based one), and that it is a dynamic language[1], what you want to do is impossible. Further, JavaScript doesn't actually have inheritance/subclassing - it has to be faked by copying and extending objects. There is no way (that I know of) to prevent other code from doing this.

  1. In a dynamic language with metaclass support, it would be possible to implement such a feature. JavaScript is not such a language.
Michael E
+7  A: 

The JavaScript Object Oriented paradigm is prototype based, that means that objects "inherit" from other objects, using them as their prototype.

There are no classes, Car is a constructor function, and the language lets you extend any virtually any object.

If you can make a Car object instance, there is no way to prevent this object being used as the prototype of other constructor function.

CMS
A: 

Nope you can't do this directly and don't know that there is a way to do this given Javascript's prototypical inheritance but take a look at Extjs, which is a js framework which has a heavy object oriented type design. Look at the api and more so the source code and you might get closer to where you want to go -- but not totally :)

non sequitor