Tautvydas
Tautvydas

Reputation: 1288

TypeScript Class how to define not prototype class function

Just starting to use TypeScript and I can't find explanation for this issue...

Lets say I have function

function test() {
    function localAccessMethod() {
        console.log('I am only accessable from inside the function :)');
    }

    this.exposedMethod = function () {
        console.log('I can access local method :P');

        localAccessMethod();
    }
}

And I want to convert this to typescript class... So far I did it up to here:

class test {

    constructor: {}

    exposedMethod() {
        console.log('I can access local method :P');

        localAccessMethod();
    }

}

How can I define that local function in the typescript class, so it wouldn't be exposed as prototype or .this... ?

Or better question, how should I convert the source code to fit TypeScript standard. I want to have function which is available for all class methods only, but is not exposed...

Upvotes: 4

Views: 1128

Answers (2)

ktretyak
ktretyak

Reputation: 31721

You can to use private static keywords:

class Test
{
  private static localAccessMethod()
  {
    console.log('I am only accessable from inside the function :)');
  }

  exposedMethod()
  {
    console.log('I can access local method :P');
    Test.localAccessMethod();
  }
}

Upvotes: 2

Nitzan Tomer
Nitzan Tomer

Reputation: 164217

You can't have something in a class which won't be exposed, even private/protected members/methods are exposed in javascript and only the compiler enforces this visibility.

You have a few options:

(1) Have the "inner" function inside the main one:

export class test {
    constructor() {}

    exposedMethod() {
        console.log('I can access local method :P');

        function localAccessMethod() {
            console.log('I am only accessable from inside the function :)');
        }

        localAccessMethod();
    }
}

(2) If this is a module then place the inner function in the top level part of the module and don't export it:

function localAccessMethod() {
    console.log('I am only accessable from inside the function :)');
}

export class test {
    constructor() {}

    exposedMethod() {
        console.log('I can access local method :P');

        localAccessMethod();
    }
}

(3) If you're not using modules then wrap this thing in a namespace and export only the class:

namespace wrapping {
    function localAccessMethod() {
        console.log('I am only accessable from inside the function :)');
    }

    export class test {
        constructor() {}

        exposedMethod() {
            console.log('I can access local method :P');

            localAccessMethod();
        }
    }
}

Upvotes: 1

Related Questions