Is it possible to restrict inheritance in javascript ? I searched internet about restricting of inheritance in javascript but didn't find any useful information.Can someone explain on this topic of inheritance restriction ? I would like to restrict inheriting properties of my singleton object in other objects.
1 Answer
You cannot restrict inheritance in javascript. If you have a public constructor function that initializes an object, any other object can use it to make a derived object.
You can make many instance variables or even methods private with certain methods of declaration (see here for reference) which can reduce the usefulness or capabilities of a derived object though still doesn't prevent it.
Perhaps if you explain what problem you're really trying to solve, we could offer more concrete ideas on how to solve it.
OK, now that you've explained that you just want a singleton, then I'd suggest you use a singleton design pattern like this:
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
The constructor is private (contained within the closure) so it can't be called by other code and the means of getting the object is a function that only ever returns the single instance. Of course, any properties/methods on an object in JS can be copied, but a singleton like this can keep instance data in the closure if it wants where it cannot be copied.
References:
Learning Javascript Design Patterns - The Singleton Pattern
sealed,final, etc. attributes. You can hide the constructor, if it has one, with a closure. But, inheritance in JavaScript is based in objects rather than classes, so an instance can always be created with justObject.create(singleton).