简体   繁体   中英

Typescript Class with private variables

Need help to write following javascript code in typescript, it is a simple class with two public functions:

var Myclass =   (function  ()
{
var teststr = ['ein test','noch ein test'];

function Myclass (){
    this.test();
}
function getStr (id) {
    return teststr[id];
}
Myclass.prototype.test = function ()
{
    console.log(getStr(0))
    this.test1();
}
Myclass.prototype.test1 = function ()
{
    console.log(getStr(1))
}
return Myclass;
})();
var instMyClass = new Myclass();
  • var instMyClass call the constructor, than the constructor call public function test.
  • function test give out the first element of private array teststr and call public function test1
  • function test1 give out the second elemement of private array teststr

i try this solution, bur typescript compilier shows errors

class Myclass {
private teststr:Array<string> = ['ein test','noch ein test'];
constructor() {
    this.test();
}
function getStr() {
    return teststr[id];
}
test() {
console.log(getStr(0));
    this.test1();
}
test1(str:string) {
console.log(getStr(1));
}
}

let instMyclass = new Myclass();

if i try a private function with a form.submit, than the function is undefined:

class Ticket {

private form: HTMLFormElement;

constructor() {

    this.form = document.forms[0]!
    this.form.onsubmit = this.submit;
}
private setUser (user: TicketUser):void {
    console.log('ticket setUser',user);
}
public submit ():any {
    console.log('ticket submit');
    this.setUser({name:'stefan',age:100});
    return false;
}
}

Can you try with the typescript code below . Updated my answer

ts file

class Ticket {

    private form: HTMLFormElement;

    constructor(elem: HTMLFormElement) {

        this.form = elem;
        //this.form.onsubmit = this.submit();
    }
    private setUser(user: TicketUser): void {
        console.log('ticket setUser', user);
    }
    public submit(): any {
        console.log('ticket submit');
        this.setUser({ name: 'stefan', age: 100 });
        return false;
    }
}

class TicketUser {

    name: string;
    age: number;
}

window.onload = () => {
    var btn = document.getElementById("btn");
    btn.onclick = function () {
        var form = document.forms[0];
        var ticket = new Ticket(form);
        form.onsubmit = ticket.submit();

    }
};

HTML

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />

</head>
<body>
    <h1>TypeScript test</h1>

    <form id="myform" action="#"></form> <br />
    <button id="btn">click me</button>
    <script src="test.js"></script>
</body>
</html>

You can use getter/setter for what you are trying to do.
Firstly you forgot the 'this' to call variables and functions withing class.
Secondly you don't use function, you use private, publict and protected to declare them.
See the example below on how to build, instantiate and use a class.

class Myclass {
private teststr: Array<string> = ['ein test','noch ein test'];

constructor() {
    this.test();
}

public getStr(id): string {
    return this.teststr[id];
}

public setStr(str: string) {
    this.teststr.push(str);
}

private test() {
    console.log('This works, calling withing class functions within class');
}

private test1(str:number) {
    console.log(this.getStr(1));
}
}

let instMyclass = new Myclass();
instMyclass.setStr('Another String');
let x = instMyclass.getStr(2);
console.log(x);

If you have tsc compiler install do this:

tsc myfilename.tsc
node myfilename.js

and you should see the output.

You can now use private access fields in TypeScript:

class Person {
  #address = '221B, Baker Street, London';
  
  checkAddress(address: string) {
      return this.#address === address;
  }
}

Read more about this in my article here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM