Take the 2-minute tour ×

Can a method in javascript be final? How to avoid it to be overriden by a subclass?

share|improve this question
I don't believe there's any way to do this, due to the nature of JavaScript "inheritance". –  Pointy Apr 26 '11 at 22:01
Can't be done in javascript –  Avitus Apr 26 '11 at 22:02

3 Answers 3

up vote 3 down vote accepted

In the traditional sense, no, you can't have private/protected methods or prevent them from being overridden.

What you can do, however, is encapsulate methods in a scope and then simply not expose them:

function foo(){
    function bar(){
        // private function

    this.doSomething = function(){

That's about as close as you can get. I wrote an article on this a while ago: http://www.htmlgoodies.com/primers/jsp/article.php/3600451/Javascript-Basics-Part-8.htm

You can also use __defineGetter__ and __defineSetter__ to prevent access, but those aren't 100% cross-browser.

var x = {};
x.__defineGetter__('foo', function(){ return 10; });
x.__defineSetter__('foo', function(){});

x.foo = 'bar';
x.foo; // 10
share|improve this answer
great article by the way! –  ramon_salla Apr 27 '11 at 15:06

You can use defineProperty for what member you want to make secure.

Mike has mentioned configurable attribute for preventing from redefine -- delete. I'm adding this too.

function final(obj, members) {
        var m = members[i];
        if (obj.hasOwnProperty(m)) {
            Object.defineProperty(obj, m, { 
                value: obj[m],
                writable: false,
                configurable: false 
    return obj;
var obj = { foo: "bar" };
obj = final(obj, ["foo"]);

obj.foo = ""; // output will be empty but
obj.foo // now output's still bar.

Another option

Object.freeze. But it's secures all members in object.

var obj = { foo: "bar" };
obj = Object.freeze(obj);

obj.foo = ""; // output is empty
obj.foo // output is still "bar".
share|improve this answer
You can make a single property frozen by marking it configurable: false and defining it in terms of a getter. See developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… –  Mike Samuel Apr 26 '11 at 22:38
Only Ie7 support in my work. So We can't Use defineProperty. –  ramon_salla Apr 27 '11 at 15:05

As far as I know, the language does not have a way of enforcing finality of object properties. You have to enforce this on your end. One way to be "pretty sure" is to use a naming convention that is extremely unlikely to be used in a subclass. something like


Would probably work pretty well. Another option is to use the hasOwnProperty() function to detect if a parent object already has a property before overwriting it with something else.

share|improve this answer
EcmaScript 5 has added property descriptors to allow for things like this. –  Mike Samuel Apr 26 '11 at 22:39

Your Answer


