0

Below typescript code

class MyClass{
     test1 = function(){    
     }       
     test2(){   
     }
}

generates

var MyClass = (function () {
    function MyClass() {
        this.test1 = function () {
        };
    }
    MyClass.prototype.test2 = function () {
    };
    return MyClass;
})();

I used to have javascript named function within a module, normally for recursion etc. Is it possible to have a function, within a class, assigned to a variable, or a named function which is not part of prototype or this. something like test3 and test4 below.

    var MyClass = (function () {
        function test3(){    
        }  
        var test4 = function(){     
        }
        function MyClass() {
            this.test1 = function () {
                //test3 and test4 are accessible here..
            };
        }
        MyClass.prototype.test2 = function () {
        };
        return MyClass;
    })();
2
  • What do you mean, for recursion? Maybe a closure? Commented Mar 23, 2014 at 20:17
  • like, recur(pid){ ... ;...; _.each(ch, (c) => {...; recur(c.Id)}} ; . I thought it is neater not to add recur to prototype, though it works. Commented Mar 23, 2014 at 22:37

1 Answer 1

2

Use the static keyword prior to the function, and it will be bound to the function constructor only, not the prototype or this. There is no way to make it completely hidden within the closure.

TypeScript

class MyClass{
    static test1 = function(){    
    }       
    test2(){
    }
}

JavaScript

var MyClass = (function () {
    function MyClass() {
    }
    MyClass.prototype.test2 = function () {
    };
    MyClass.test1 = function () {
    };
    return MyClass;
})();
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer +1. You can additionally mark it as private and typescript will prevent you from using it externally private static test1 = function(){ (not really private but it is sufficient if you use TS)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.