Search code examples
javascriptoopfinal

javascript final method


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


Solution

  • 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(){
            bar();
        }
    }
    

    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